<?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 Shitanshu Pandey on Medium]]></title>
        <description><![CDATA[Stories by Shitanshu Pandey on Medium]]></description>
        <link>https://medium.com/@thisis-Shitanshu?source=rss-960d2399f388------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NQqZUEi74WxpfJcKqbRObg.png</url>
            <title>Stories by Shitanshu Pandey on Medium</title>
            <link>https://medium.com/@thisis-Shitanshu?source=rss-960d2399f388------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:04:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thisis-Shitanshu/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[Beyond the Cycle]]></title>
            <link>https://medium.com/@thisis-Shitanshu/beyond-the-cycle-69b095e540e6?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/69b095e540e6</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[existentialism]]></category>
            <category><![CDATA[space]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 07:15:50 GMT</pubDate>
            <atom:updated>2026-11-10T07:15:50.856Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reflections after Reading Ben Bolte’s “Peering Over the Waterfall”</h4><blockquote>Peering Over the Waterfall: <a href="https://ben.bolte.cc/posts/2026-11-08-agi/">https://ben.bolte.cc/posts/2026-11-08-agi/</a></blockquote><p>There is a certain luxury that comes with civilizational stability: the freedom to contemplate questions larger than one’s immediate survival.</p><p>But stability need not always come from civilization itself. Some individuals can create a kind of artificial stability, even amid chaos, carving out enough space in their lives and minds to contemplate questions beyond their immediate circumstances.</p><p>For much of human history, and for many people even today, life has been dominated by the necessity of securing food, shelter, safety, and continuity. Yet when a civilization develops enough stability, whether through institutions, technology, or accumulated knowledge, it creates room for individuals to question the nature of existence itself.</p><p>Are we living in a simulation? Is our experience predetermined? Is there some larger pattern governing everything?</p><p>I am not particularly convinced by the simulation hypothesis. But I can understand why reality sometimes appears to possess the characteristics of a simulation.</p><p>Perhaps what we interpret as evidence of a simulated reality is, at least partly, our recognition of recurring patterns in nature.</p><p>Consider celestial motion. Earth rotates on its axis while orbiting the Sun. The Sun, together with our solar system, moves around the center of the Milky Way. The galaxy itself moves through a universe filled with other galaxies.</p><p>Across vastly different scales, we encounter periodic motion, cycles, and recurring relationships.</p><p>Our daily experience is already governed by some of these cycles. Day follows night. Seasons return. Organisms reproduce, civilizations emerge, institutions rise and decline, and generations repeatedly confront problems that earlier generations believed they had solved.</p><p>Perhaps the feeling of living in a loop emerges not because reality is being replayed, but because we exist inside systems whose underlying processes repeat.</p><p>This makes me wonder about the intellectual origins of Jyotisha in ancient India.</p><p>Could the observation of celestial regularity have encouraged the idea that sufficiently understanding recurring astronomical phenomena would allow people to anticipate future earthly circumstances?</p><p>At the level of seasons, calendars, and agricultural planning, this intuition has practical value. If celestial patterns allow us to measure time and anticipate seasonal changes, then perhaps ancient observers sought to extend similar reasoning to the lives of communities and individuals.</p><p>And that brings me to a more fundamental question.</p><p><strong>If so much of existence is structured around recurring patterns, what is the point of it all?</strong></p><p>I suspect the answer lies in distinguishing recurrence from repetition.</p><p>A cycle may return without producing exactly the same outcome. The environment changes, the participants change, and the consequences of previous cycles accumulate.</p><p>Life does not necessarily begin again from the same starting point.</p><p>We inherit the knowledge, tools, mistakes, and achievements of those who came before us. Each generation receives a world shaped by previous generations and, through its own decisions, changes the conditions inherited by those who follow.</p><p>This is where I find meaning.</p><p>I think of light traveling through the universe, encountering matter, reflecting, scattering, being absorbed, and sometimes being emitted again. Its journey is shaped by its interactions.</p><p>Perhaps human civilization has a similar responsibility, not physically as light does, but in what it carries forward.</p><p>We encounter circumstances we did not choose. We absorb experiences, develop understanding, and pass something onward. Sometimes that contribution is knowledge. Sometimes it is a technology, an institution, an idea, or simply a better way of living.</p><p>The purpose is not merely to endure another cycle.</p><p>It is to survive, learn, adapt, and become more capable than we were before, while increasing the possibility that those who follow us can do the same.</p><p>Progress is not inevitable. Civilizations can lose knowledge, repeat destructive mistakes, or fail to survive the consequences of their own capabilities. That is precisely why understanding the past matters.</p><p>We should study where we came from, not simply to preserve history, but to recognize patterns, understand their causes, and avoid repeating failures that are within our power to prevent.</p><p>And we should study where we are going, because survival without direction cannot be the entirety of our ambition.</p><p>Perhaps we will never know whether the universe has an ultimate purpose. But we can still choose a purpose for ourselves within it.</p><p>To understand more of reality. To extend the boundaries of what life can accomplish. To build civilizations capable of lasting longer, knowing more, and reaching farther.</p><p><strong>The greatest adventure of human civilization may be to understand where the light comes from, discover where it can go, and become capable of carrying it farther.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmM3pCA6MWxujMwxiXtURg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69b095e540e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kelsey Hightower’s Zero Token Architecture (ZTA)]]></title>
            <link>https://medium.com/@thisis-Shitanshu/kelsey-hightowers-zero-token-architecture-zta-11489d0eef8e?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/11489d0eef8e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 10:31:06 GMT</pubDate>
            <atom:updated>2026-07-16T10:31:06.251Z</atom:updated>
            <content:encoded><![CDATA[<h4>What Kelsey’s ideas about agentic loops teach us about building cheaper, simpler, and more maintainable AI systems</h4><p>I watched this talk recently, and every minute was worth learning from.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FA7WFt2JQ5sg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DA7WFt2JQ5sg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FA7WFt2JQ5sg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/743480b7f31e0a0d9259511d943210a9/href">https://medium.com/media/743480b7f31e0a0d9259511d943210a9/href</a></iframe><p>Kelsey discussed a problem that is becoming increasingly important as companies rush to add AI agents to their products and infrastructure.</p><p>Many developers are using LLMs to perform the same tasks repeatedly. Every time the task runs, the model reads instructions, reasons about the problem, generates an answer, and consumes more tokens.</p><p>But what happens when the problem has already been solved?</p><p>Do we really need an AI model to think through the same steps every time?</p><p>Kelsey’s answer is a simple but powerful idea:</p><blockquote><em>Infer once, export the logic, and run it without further inference.</em></blockquote><p>This approach is sometimes described as <strong>Zero Token Architecture</strong>.</p><p>It does not mean that we should never use AI. It means we should use AI where intelligence and discovery are required, and then convert repeated solutions into standard software.</p><p>I want to share my takeaways from this amazing talk.</p><h3>1. The Problem With Agentic Loops</h3><p>An AI agent usually works in a loop. It observes the current situation, decides what to do, uses a tool, checks the result, and continues until the task is complete.</p><p>A simple agentic loop may look like this:</p><pre>Understand the request<br>        ↓<br>Decide the next action<br>        ↓<br>Call a tool<br>        ↓<br>Check the result<br>        ↓<br>Repeat</pre><p>This approach is useful when the task is uncertain.</p><p>For example, an AI agent may help investigate an unusual production failure. It may need to inspect logs, examine different services, search documentation, test possible causes, and change its plan based on what it discovers.</p><p>In that situation, a fixed script may not be enough.</p><p>The problem begins when we use the same agentic loop for a repetitive and predictable task.</p><p>Imagine asking an AI agent to create the same kind of database table every time a new service is launched.</p><p>The agent may repeatedly:</p><ol><li>Read the requirements (eg: CSV).</li><li>Decide which columns are needed.</li><li>Generate SQL.</li><li>Run the SQL.</li><li>Check for errors.</li><li>Correct the SQL.</li><li>Try again.</li></ol><p>This process consumes tokens every time, even when the final structure is almost identical.</p><p>We are paying the model to solve a problem that has already been solved.</p><h3>2. What Zero Token Architecture Actually Means</h3><p>Zero Token Architecture is a design philosophy. The idea is to use an AI model during the uncertain stage of a problem, then move the discovered solution into normal software.</p><p>The process looks like this:</p><pre>Use AI to understand the problem<br>        ↓<br>Generate and improve the solution<br>        ↓<br>Export the solution as code or configuration<br>        ↓<br>Review and test it<br>        ↓<br>Run it repeatedly without AI</pre><p>The word “zero” should not be taken literally. Tokens may still be used during the initial design process. AI may also be used again when requirements change or a completely new problem appears.</p><p>The goal is to reach zero repeated token usage for tasks that are already understood.</p><p>In simple terms:</p><blockquote><em>Use AI for thinking. Use software for repetition.</em></blockquote><h3>3. Use the Agent for Discovery</h3><p>The first lesson is to use the agent where it provides the most value.</p><p>AI models are good at working through complexity. They can examine requirements, compare possible approaches, explain unfamiliar systems, generate initial code, and help engineers discover useful patterns.</p><p>For example, suppose a company needs a deployment system for several applications.</p><p>The company may have:</p><ul><li>Go API services</li><li>Node.js web applications</li><li>Python background workers</li><li>Different testing requirements</li><li>Different deployment environments</li><li>Rollback and monitoring requirements</li></ul><p>An AI agent can study these requirements and help answer important questions:</p><ul><li>Which deployment process should be used?</li><li>Which steps are common across all services?</li><li>Which parts need separate handling?</li><li>How should failures be detected?</li><li>How should rollbacks work?</li><li>Which configurations should be reusable?</li></ul><p>This is a good use of AI because the team is still discovering the structure of the solution.</p><p>The agent is helping the engineers navigate uncertainty.</p><p>However, after the design becomes clear, the company should not ask the model to redesign the deployment process every time an application is released.</p><p>The discovered process should become software.</p><h3>4. Export the Logic</h3><p>The next step is to take the useful result out of the AI conversation.</p><p>An AI response should not remain only as text inside a chat window or as part of another prompt.</p><p>The result can be exported as:</p><ul><li>Source code</li><li>A shell script</li><li>A database migration</li><li>A configuration file</li><li>A reusable library</li><li>A command-line tool</li><li>A Terraform module</li><li>A CI/CD workflow</li><li>A compiled binary</li><li>A framework component</li></ul><p>Suppose an agent discovers that all company services belong to three main categories:</p><ol><li>Go API services</li><li>Node.js applications</li><li>Python workers</li></ol><p>The team can create three reusable pipeline templates:</p><pre>go-service-pipeline.yaml<br>node-service-pipeline.yaml<br>python-worker-pipeline.yaml</pre><p>Each repository can then use the correct template. The AI helped the team discover the abstraction, but the abstraction now exists independently of the AI. This is what it means to export the logic.</p><h3>5. Normalize the AI-Generated Output</h3><p>AI-generated code should not immediately be treated as production-ready software. It must go through the same engineering process as any other code.</p><p>The team should:</p><ul><li>Review the code</li><li>Remove unnecessary complexity</li><li>Add error handling</li><li>Write automated tests</li><li>Check security risks</li><li>Improve performance</li><li>Add documentation</li><li>Follow coding standards</li><li>Store it in version control</li><li>Assign ownership for maintenance</li></ul><p>This step is important because AI-generated code can contain incorrect assumptions, insecure patterns, missing edge cases, or outdated practices.</p><p>Zero Token Architecture does not remove the need for software engineering. It makes software engineering more important.</p><p>The model may help create the first version, but humans must decide whether the final result is safe, reliable, and maintainable.</p><h3>6. Run the Solution Without Inference</h3><p>Once the exported solution has been reviewed and tested, it can run as normal software. The CPU follows the instructions directly.</p><p>For example, a deployment may become:</p><pre>Developer pushes code<br>        ↓<br>CI pipeline starts<br>        ↓<br>Automated tests run<br>        ↓<br>Deployment script executes<br>        ↓<br>Health checks confirm success</pre><p>An AI model does not need to decide how deployment works every time.</p><p>This creates several benefits.</p><ul><li>Lower cost: Normal computation is usually much cheaper than repeated calls to a large language model.</li><li>Faster execution: The system does not need to send prompts to a model and wait for generated responses.</li><li>Predictable behaviour: The same input produces the same expected process.</li><li>Easier testing: Engineers can write unit tests, integration tests, and security tests for the exported code.</li><li>Easier debugging: When something fails, the team can inspect the exact code and execution logs.</li><li>Better control: The system does not depend on a model generating the correct answer during every run.</li></ul><p>AI is used to create the tool. The tool is then used to perform the task.</p><h3>7. Treat AI as a Consultant, Not a Permanent Contractor</h3><p>One of the easiest ways to understand this philosophy is to think of AI as an expert consultant.</p><p>Imagine hiring an expert to analyse a difficult business process. The expert studies the problem, designs a solution, builds a tool, and documents how the process should work. After the tool is built, the company uses it every day. The company does not hire the same expert every morning to rebuild the tool from the beginning. That would be expensive and unnecessary.</p><p>The same principle applies to AI.</p><p>A poor approach is:</p><pre>Task appears<br>        ↓<br>Pay the AI to solve it<br>        ↓<br>Task appears again<br>        ↓<br>Pay the AI to solve it again</pre><p>A better approach is:</p><pre>Pay the AI to understand the task<br>        ↓<br>Build a reusable solution<br>        ↓<br>Run the solution whenever needed</pre><p>The AI should return when a new problem appears, the requirements change, or the existing tool needs to be redesigned.</p><h3>8. Do Not Use AI to Hide Bad Infrastructure</h3><p>Another important lesson from the talk is that adding an AI agent does not automatically improve the underlying system.</p><p>Imagine a deployment platform that requires 40 confusing manual steps.</p><p>One solution is to build an AI agent that performs all 40 steps. The process may become easier for the user, but the infrastructure is still complicated. The agent is managing the complexity rather than removing it.</p><p>A better question would be:</p><blockquote><em>Why does deployment require 40 steps in the first place?</em></blockquote><p>Perhaps the platform can be redesigned so that deployment requires only one command: deploy-service payments</p><p>This removes complexity instead of hiding it.</p><p>AI agents can become another layer placed on top of difficult infrastructure:</p><pre>Complicated infrastructure<br>        ↓<br>Complicated management tools<br>        ↓<br>AI agent to operate the tools<br>        ↓<br>Another system to monitor the agent</pre><p>Every new layer adds cost, failure points, security concerns, and maintenance work.</p><p>Sometimes an agent is the right solution. In other situations, the better solution is to redesign the system underneath it.</p><h3>9. Real Innovation Comes From Understanding Fundamentals</h3><p>Kelsey also connects this idea to the history of computing.</p><p>Major platform changes did not happen only because someone automated an existing process. They happened because engineers deeply understood the original problem and created a better foundation.</p><p>Containers are a useful example.</p><p>Before containers became common, deploying applications often involved installing dependencies directly on servers and managing differences between environments.</p><p>Containers introduced a standard way to package applications with their dependencies.</p><p>This was not simply an intelligent tool performing old deployment steps. It changed the underlying way applications were packaged and executed.</p><p>This kind of innovation requires knowledge of fundamentals, including:</p><ul><li>How operating systems schedule processes</li><li>How memory is managed</li><li>How network connections work</li><li>How databases store and index data</li><li>How compilers transform code</li><li>How containers isolate processes</li><li>How distributed systems fail</li><li>How authentication and encryption work</li></ul><p>Engineers who understand these areas can identify problems in the foundation. They can ask:</p><ul><li>Why does this system need to be so complicated?</li><li>Can this entire workflow be removed?</li><li>Can we design a better interface?</li><li>Can we create a simpler platform?</li><li>Is this tool solving the problem or only hiding it?</li></ul><p>AI can help engineers answer these questions, but it should not replace the curiosity required to ask them.</p><h3>10. Engineers Should Be Historians of Technology</h3><p>Understanding the history of technology helps us understand why current systems exist. Engineers should study questions such as:</p><ul><li>Why were containers created?</li><li>Why did virtual machines become popular?</li><li>Why was Kubernetes needed?</li><li>Why do relational databases use SQL?</li><li>Why did microservices become popular?</li><li>Which older distributed systems failed?</li><li>Which ideas were abandoned, and why?</li></ul><p>Without historical understanding, we may repeat old mistakes with new names. An AI-powered architecture may appear completely new while repeating a design that previously failed, with an LLM added on top.</p><p>History helps engineers distinguish between:</p><ul><li>A genuinely new idea</li><li>An old idea with new branding</li><li>A temporary workaround</li><li>A useful abstraction</li><li>An unnecessary layer</li><li>A long-term platform improvement</li></ul><p>Knowing how we reached the current system also makes it easier to imagine what should replace it.</p><h3>11. The Risk of Becoming Too Dependent on AI</h3><p>Kelsey warns about engineers losing their “batting average.”</p><p>In this context, batting average means the ability to keep experimenting, testing ideas, learning from failure, and occasionally creating an important improvement. Innovation rarely comes from the first attempt.</p><p>The process usually looks like this:</p><pre>Try an idea<br>        ↓<br>Discover weaknesses<br>        ↓<br>Improve the design<br>        ↓<br>Try again</pre><p>If engineers depend completely on AI-generated solutions, they may slowly stop practising important skills:</p><ul><li>Designing systems independently</li><li>Reading source code</li><li>Understanding low-level behaviour</li><li>Debugging difficult failures</li><li>Testing new abstractions</li><li>Challenging existing architecture</li><li>Learning from failed experiments</li></ul><p>They may become good at asking AI to produce code while becoming less capable of judging whether the code represents a good system.</p><p>AI should increase an engineer’s ability to experiment. It should not remove the engineer from the process of understanding.</p><h3>12. When Agentic Loops Are Still Useful</h3><p>Zero Token Architecture does not mean that all agentic systems are bad. Agents are useful when the task is open-ended, uncertain, or highly variable. Examples include:</p><ul><li>Investigating an unusual production incident</li><li>Researching an unfamiliar subject</li><li>Understanding unstructured documents</li><li>Responding to unique customer problems</li><li>Planning a new product</li><li>Analysing changing requirements</li><li>Working with incomplete information</li></ul><p>These tasks cannot always be reduced to a fixed set of instructions.</p><p>A useful rule is:</p><pre>Stable and predictable task → Use normal software<br>Changing and uncertain task → Consider using an AI agent</pre><p>The mistake is not using agents. The mistake is using agents for every task, including tasks that should already have become deterministic software.</p><h3>13. The Best Approach Is Often Hybrid</h3><p>The most practical architecture combines AI with normal software. The system should first check whether the request can be handled by deterministic code.</p><pre>New request<br>        ↓<br>Can normal software handle it?<br>        ↓<br>Yes → Run the existing code<br>No → Ask the AI to analyse it</pre><p>When AI solves a new type of problem, the team should ask another question:</p><pre>Can this solution be reused?<br>        ↓<br>Yes → Convert it into code or configuration<br>No → Keep it as an AI-assisted case</pre><p>This allows the system to improve over time.</p><p>Repeated patterns discovered by the AI can gradually become:</p><ul><li>Functions</li><li>Rules</li><li>Templates</li><li>Libraries</li><li>Validation systems</li><li>Workflows</li><li>Configuration files</li><li>Platform features</li></ul><p>The AI handles uncertain edge cases, while normal software handles the stable majority of requests. This approach gives teams the flexibility of AI without making every operation dependent on expensive inference.</p><h3>14. A Simple Practical Example</h3><p>Imagine a company regularly receives CSV files from customers. Each file must be checked, transformed, and imported into a database.</p><p>A fully agentic approach may send every file to an AI model.</p><p>The model may:</p><ol><li>Inspect the columns.</li><li>Understand the format.</li><li>Generate validation rules.</li><li>Create database commands.</li><li>Insert the records.</li><li>Repeat the process for the next file.</li></ol><p>This may be useful during the early stage when the formats are unknown. After analysing enough files, however, the company may discover that most customers use only five common formats. The team can then build a standard importer:</p><pre>customer-importer data.csv --schema customer-v2</pre><p>Normal files are processed without AI. Only unknown formats are sent to the agent for analysis.</p><p>The architecture becomes:</p><pre>Known file format → Standard importer<br>Unknown file format → AI analysis</pre><p>This is cheaper, faster, easier to test, and easier to maintain. It also demonstrates the central principle:</p><blockquote><em>When uncertainty becomes a pattern, convert the pattern into software.</em></blockquote><h3>Conclusion</h3><p>Kelsey’s message is not that we should stop using AI agents. The message is that we should use them carefully.</p><p>AI is most valuable when the path is unclear, the information is unstructured, or the solution has not yet been discovered. Once a task becomes stable and repeatable, we should export the intelligence into code, scripts, libraries, configurations, frameworks, or binaries.</p><p>This creates a simple engineering principle:</p><blockquote><em>Let AI discover the process. Let software repeat the process.</em></blockquote><p>We should also avoid placing AI agents on top of badly designed infrastructure without questioning the infrastructure itself.</p><p>The goal should not be to build agents that can operate increasingly complicated systems forever. The goal should be to use our understanding, including insights gained from AI, to build simpler and better systems.</p><p>AI should help engineers create the next generation of computing platforms. It should not trap them inside the current generation by making old complexity easier to tolerate.</p><p>Zero Token Architecture gives us a useful direction:</p><blockquote><strong>Infer once. Export the logic. Test it properly. Run it natively. Bring the AI back only when something genuinely new needs to be solved.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRibX3JiB-wRuICv9hiuww.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11489d0eef8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Hospitality Lakehouse Data Platform]]></title>
            <link>https://medium.com/@thisis-Shitanshu/building-a-hospitality-lakehouse-data-platform-68346d5f58cf?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/68346d5f58cf</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 16:50:45 GMT</pubDate>
            <atom:updated>2026-07-07T16:50:45.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing a data platform for bookings, revenue, occupancy, payment reconciliation, and demand forecasting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_m0blHSpaoCBfkTAsad3w.png" /></figure><p>Hospitality companies run on operational decisions.</p><p>Every booking, cancellation, payment, refund, room availability change, customer review, and support issue affects revenue, pricing, hotel operations, and customer experience. If the data is late, inconsistent, or difficult to trust, the business team cannot make good decisions.</p><p>Here we’re building a data platform for a hospitality business.</p><p>The system starts with operational events such as bookings, payments, refunds, room inventory, and reviews. These events are published to Kafka and stored as raw bronze data, cleaned with Spark, organized into Iceberg silver tables, transformed into gold marts and feature tables, served to business users through Snowflake and Metabase, and connected to the demand forecasting workflow using MLflow and DVC.</p><p>This is not just a pipeline; this is a complete data platform.</p><p>The final system follows this flow:</p><p>&gt; Kafka</p><p>&gt; Bronze object storage</p><p>&gt; Spark processing</p><p>&gt; Iceberg silver tables</p><p>&gt; Iceberg gold marts and feature tables</p><p>&gt; Snowflake BA-serving schema</p><p>&gt; Metabase dashboards</p><p>&gt; MLflow/DVC-backed demand forecasting</p><p>&gt; Airflow orchestration, quality check, runbooks, cost/ security controls</p><p>The project is designed around a simple business question:</p><blockquote>For each hotel, room type, date, and channel, what happened, why it happened, and what should the business do next?</blockquote><p>That question connects data engineering directly to business values.</p><p>A hospitality company needs to know:</p><ul><li>How many bookings were created?</li><li>How many were cancelled?</li><li>How much revenue was actually earned?</li><li>Which payments were successful?</li><li>Which refunds are pending?</li><li>Which hotels are underperforming?</li><li>Which cities are seeing demand growth?</li><li>Which room types are selling out?</li><li>Which channels bring high-quality bookings?</li><li>What demand can be expected over the next few days?</li></ul><p>To answer these questions reliably, we need more than dashboards.</p><p>We need a data platform with clear layers.</p><p>Bronze keeps the raw truth. Silver cleans and standardizes the data. Gold creates business-ready marts. The warehouse serves analysts and business users. The ML layer uses curated feature tables, so forecasting is reproducible.</p><p>Let’s get started! 🚀</p><h3>Section 0: Setup and Considerations</h3><p>Before writing the first data generator or Kafka producer, we need to make the project practical.</p><p>A common mistake in data engineering is trying to run the entire modern data stack at once. Kafka, Spark, Iceberg, Airflow, MinIO, Snowflake, Metabase, MLflow, DVC, Prometheus, Grafana, and Terraform are all useful tools, but running everything together on a local machine can make the project slow and unstable.</p><p>So this project uses a hybrid approach.</p><p>The platform is designed like a production system, but it is executed locally in small profiles. Each profile runs only the services needed for one part of the project.</p><p>For example:</p><ul><li>The bronze profile runs Kafka and object storage.</li><li>The silver profile runs Spark and Iceberg jobs.</li><li>The BI profile runs Metabase.</li><li>The ML profile runs MLflow and model jobs.</li><li>The cloud profile is used only for selected AWS and Snowflake integrations.</li></ul><p>This keeps the project hardware-aware.</p><blockquote>The local system does not need to pretend to be a production cluster. It needs to prove that the design is correct, the data contracts are clear, the transformations are reliable, and the business outputs are useful.</blockquote><p>The project uses the following principles.</p><p><strong>1. Business-first design</strong></p><p>This platform is not built around tools first. It is built around hospitality decisions. The main business outputs are:</p><ul><li>Daily booking mart</li><li>Daily revenue mart</li><li>Occupancy mart</li><li>Payment and refund reconciliation mart</li><li>Cancellation mart</li><li>Demand forecasting feature table</li><li>Forecasting output table</li><li>Business dashboard</li></ul><p>Every technical component should support one of these outputs.</p><p><strong>2. Raw data should be immutable</strong></p><p>The bronze layer stores raw events exactly as received.</p><p>If a booking event arrives from Kafka, we do not overwrite it. We store it with metadata such as ingestion time, source topic, partition, offset, and event date.</p><p>This allows replay, audit, debugging, and backfilling.</p><p><strong>3. The silver table should be clean and typed</strong></p><p>The silver layer fixes the shape of the data.</p><p>This is where we parse timestamps, cast amounts to decimal types, validate status values, remove duplicates, and quarantine bad records.</p><p>A dashboard should never depend directly on raw JSON.</p><p><strong>4. Gold marts should match business questions</strong></p><p>The gold layer is where the engineering work becomes business value.</p><p>For example, revenue should not be a random sum of booking amounts. It should follow a clear definition.</p><p>A booking may be created, paid, cancelled, partially refunded, or fully refunded. The revenue mart should reflect the business meaning of revenue, not just the raw booking price.</p><p><strong>5. The warehouse should serve business users</strong></p><p>The lakehouse is useful for engineering, reproducibility, and scalable processing.</p><p>But business users usually need stable SQL tables, access control, and dashboard performance. That is why the selected gold marts are loaded into Snowflake and served through Metabase.</p><p><strong>6. ML should use the same trusted data</strong></p><p>The demand forecast model should not use a separate private dataset.</p><p>It should use the same curated feature table created from gold data. This avoids a mismatch between analytics numbers and model training data.</p><p><strong>7. Local execution should be staged</strong></p><p>On a small machine, it is better to run one layer at a time.</p><p>This project uses Docker Compose profiles and Makefile commands to start only what is needed.</p><p>The project should be easy to stop, reset, and re-run.</p><p><strong>8. Cloud should be selective</strong></p><p>The project uses local MinIO as an S3-compatible object store during development.</p><p>AWS is used selectively for S3, IAM, budget alerts, and Terraform practice. Expensive services such as EKS, MSK, and EMR are intentionally avoided in the first version.</p><p>This is not a shortcut. It is a cost-aware engineering decision.</p><p><strong>9. Every pipeline should be observable</strong></p><p>A pipeline is not complete just because it runs once.</p><p>Each pipeline should answer:</p><ul><li>Did it run?</li><li>When did it run?</li><li>How many records were processed?</li><li>How many failed?</li><li>Was the schema valid?</li><li>Was the data fresh?</li><li>Can we safely retry it?</li><li>Can we backfill it?</li><li>Who should be informed if it fails?</li></ul><p>These questions are part of the design from the beginning.</p><p><strong>10. The repository should explain the system</strong></p><p>The repository is not only code. It includes:</p><ul><li>Architecture diagram</li><li>Data model</li><li>Metric definitions</li><li>Runbook</li><li>Incident response notes</li><li>Cost optimization notes</li><li>Security notes</li><li>Dashboard outputs</li><li>MLflow outputs</li><li>Snowflake query outputs</li></ul><p>I believe a complete engineering project should be understandable without requiring the reader to reverse engineer everything from code.</p><p>In this section, we create the base project structure, environment files, local configuration, Makefile, and the first setup validation script.</p><blockquote>To access the code for “Section 0: Setup and Consideration”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/928e97c825181301b9ab53076d404ff3c642129a">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*Obdv92VFwOrezwsxkj6lCw.png" /><figcaption>Fig: Python environment created, and Environment check passes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*ZUk3jXAEbCY0gw4yNLP3Dg.png" /><figcaption>Fig: MinIO starts successfully</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlEB9oZnxYkcKFFG0JsBvA.png" /><figcaption>Fig: MinIO starts successfully — 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oN2DpmOzSMM4m11oCNsweA.png" /><figcaption>Fig: Buckets are created</figcaption></figure><h3>Section 1: Data Model and Generator</h3><p>Before building Kafka pipelines, Spark jobs, Iceberg tables, Snowflake marts, dashboards, or ML workflows, we need a clear data model.</p><p>In hospitality, most analytics questions start from a few core entities:</p><ul><li>hotels</li><li>rooms</li><li>guests</li><li>inventory</li><li>bookings</li><li>payments</li><li>refunds</li><li>reviews</li></ul><p>A booking alone is not enough to understand the business.</p><p>A booking tells us that a guest reserved a room. But revenue depends on payment status. Final earnings depend on refunds. Occupancy depends on room availability. Customer experience depends on reviews. Demand forecasting depends on booking dates, stay dates, lead time, room type, city, channel, and historical demand.</p><p>So the first goal is to have a relational dataset that can support the rest of the platform.</p><p>The dataset in this section is synthetic. This is intentional.</p><p>Public hotel datasets are useful, but they usually do not contain the full operational lifecycle of a hospitality business. They may include booking records, but not always payment events, refunds, room inventory, support context, or clean business keys. For this project, synthetic data gives us control over the complete business process.</p><p>The generator creates CSV files for:</p><ul><li>sample_data/hotels.csv</li><li>sample_data/rooms.csv</li><li>sample_data/guests.csv</li><li>sample_data/inventory.csv</li><li>sample_data/bookings.csv</li><li>sample_data/payments.csv</li><li>sample_data/refunds.csv</li><li>sample_data/reviews.csv</li></ul><p>Each file has a defined grain.</p><p>The grain is important because many data quality issues come from unclear table meaning.</p><p>For example:</p><ul><li>hotels.csv has one row per hotel.</li><li>rooms.csv has one row per hotel and room type.</li><li>inventory.csv has one row per room type per stay date.</li><li>bookings.csv has one row per booking.</li><li>payments.csv has one row per payment transaction.</li><li>refunds.csv has one row per refund transaction.</li><li>reviews.csv has one row per guest review.</li></ul><p>This structure allows us to build reliable marts later.</p><ul><li>revenue mart</li><li>occupancy mart</li><li>payment reconciliation mart</li><li>cancellation mart</li><li>demand forecasting feature table</li></ul><p>The generator also includes common hospitality patterns:</p><ul><li>Bookings can be confirmed, cancelled, checked out, or no-show</li><li>Cancelled bookings may create refunds</li><li>Reviews exist only after completed stays</li><li>Inventory changes by date</li><li>Pricing changes by city, room type, weekday, and season</li><li>Bookings arrive through multiple channels</li><li>Guest identifiers avoid storing raw PII</li></ul><p>The purpose of this section is not just to create sample CSV files. The purpose is to create a business-aware data foundation. Every later pipeline will depend on this structure.</p><blockquote>To access the code for “Section 1: Data Model and Generator”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/34b319cc8f178183b6b151269d25489200ae5f25">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDQSeJv3lfSJ5McjoNDT2A.png" /><figcaption>Fig: Successfully generating data and validating the quality</figcaption></figure><h3>Section 2: Kafka to Bronze</h3><p>In the previous section, we created the core hospitality dataset: hotels, rooms, bookings, inventory, payments, refunds, and reviews.</p><p>Now we turn part of the dataset into operational events.</p><p>In a hospitality platform, many important changes happen as events:</p><ul><li>A booking is created</li><li>A payment succeeds or fails</li><li>A refund is processed</li><li>Room inventory changes</li><li>A guest review is submitted</li></ul><p>Kafka is useful here because different downstream systems may need the same events. Analytics, revenue reconciliation, inventory monitoring, pricing, forecasting, and operations dashboards can all consume the same stream without tightly coupling themselves to the source systems.</p><p>But Kafka is not the final storage layer. Kafka is the event transport and replay buffer. The bronze layer is the durable raw landing zone.</p><p>In this section, we create four Kafka topics:</p><ul><li>booking_events</li><li>payment_events</li><li>inventory_events</li><li>review_events</li></ul><p>Each producer reads a CSV file from sample_data, wraps each row in a standard event envelope, and publishes it to Kafka.</p><p>The event envelope adds metadata such as:</p><ul><li>event id</li><li>event type</li><li>event time</li><li>entity name</li><li>aggregate id</li><li>source system</li><li>schema version</li><li>producer timestamp</li><li>payload</li></ul><p>This makes the raw event easier to audit and replay later.</p><p>A bronze writer consumer reads from Kafka and writes valid events into object storage as JSON files. The files are partitioned by entity, ingest date, hour, and run id.</p><p>Invalid records are not silently dropped. They are written to a quarantine bucket with the error reason, topic, partition, offset, and raw message.</p><p>This design gives us three important guarantees:</p><ol><li>Raw events are preserved.</li><li>Bad records are inspectable.</li><li>Silver processing can later deduplicate using the event id and Kafka metadata.</li></ol><p>This section intentionally uses a single Kafka broker. This is enough for development. In production, this design can move to a managed Kafka cluster or a <a href="https://docs.confluent.io/platform/current/get-started/tutorial-multi-broker.html">multi-broker deployment</a>, but the logical flow remains the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2n89OttIVgoaLxw9xVwUNQ.png" /><figcaption>Fig: Single-node KRaft Kafka container</figcaption></figure><ul><li>In the local setup, Kafka runs as a single KRaft node inside one container. That node acts as both broker and controller. The topic may have multiple partitions, but all partitions live on the same broker, so the replication factor is 1, and broker-level fault tolerance is not provided.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vI6Bm_5UbXgdXRG6fQrJjQ.png" /><figcaption>Fig: Multi-broker deployment</figcaption></figure><ul><li>In a multi-broker deployment, Kafka runs as a cluster of brokers. Topic partitions are distributed across brokers, and each partition has replicas on other brokers. This improves availability, fault tolerance, and scalability, while the producer and consumer logic stays conceptually the same.</li></ul><blockquote>To access the code for “Section 2: Kafka to Bronze”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/a7dc8d22a5400a64fa35a60c4acba904f35f922d">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V--zLHTE7tDYzF11N0h2eQ.png" /><figcaption>Fig: Starting Kafka-MinIO and Creating topics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azB4ztyPpVkDv_s9bkzUUw.png" /><figcaption>Fig: Produced events with `make produce-section2` and Consume events into bronze</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jL_-ioRTTI1rbV2iOS4-oA.png" /><figcaption>Fig: List bronze objects and Run tests</figcaption></figure><blockquote><strong>Note:</strong> This design is <strong>at-least-once</strong>, not exactly-once. Bronze preserves raw events with Kafka metadata. I do not rely on bronze uniqueness. Deduplication and business correctness are enforced in silver.</blockquote><h3>Section 3: Spark and Iceberg Silver Tables</h3><p>In Section 2, we landed raw Kafka events into the bronze object store.</p><p>Bronze data is intentionally raw. It preserves events as received, including event metadata, Kafka topic, partition, offset, and payload. That is useful for replay, audit, and debugging.</p><p>But raw data should not directly power dashboards or business metrics. The silver layer is where raw events become clean analytical tables.</p><p>In this section, Spark reads the bronze JSONL files from object storage. Each record contains an event envelope and a nested payload. The Spark parses the envelope, extracts the payload fields, casts columns into correct data types, removes duplicate events, applies basic validation rules, and writes the results into Iceberg tables.</p><p>The silver layer creates five cleaned tables:</p><ul><li>bookings</li><li>payments</li><li>refunds</li><li>inventory</li><li>reviews</li></ul><p>Each table has a clear grain:</p><ul><li>bookings: one row per booking</li><li>payments: one row per payment transaction</li><li>refunds: one row per refund transaction</li><li>inventory: one row per room type per stay date</li><li>reviews: one row per guest review</li></ul><p>The most important design decision is that bronze remains immutable, while silver becomes trustworthy. If Kafka replays the same event, bronze may contain duplicates. That is acceptable. Silver deduplicates by event identity and Kafka metadata.</p><p>For local execution, the job rebuilds silver tables from bronze. This is simple and reliable for a small implementation. In production, the same logic can evolve into <a href="https://aws.amazon.com/blogs/big-data/use-apache-iceberg-in-a-data-lake-to-support-incremental-data-processing/">incremental Iceberg writes or merge-based updates</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0adj8x6KLMQWRGTjtftTA.png" /><figcaption>Fig: Iceberg implementation side-by-side comparison</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CY8siCq_HYKLI4KMiyj8wQ.png" /><figcaption>Fig: Booking status example, why MERGE matters</figcaption></figure><p>Iceberg is used because it gives a table structure on top of object storage. Instead of managing loose Parquet files manually, we get named tables, schema, metadata, snapshots, and cleaner read/write behaviour.</p><p>Now the platform has moved from raw event storage to clean lakehouse tables that can support gold marts, Snowflake serving, dashboards, and ML feature generation.</p><blockquote>To access the code for “Section 3: Spark + Iceberg Silver”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/35f06feb7f7dad24d65f901fa3b9148e1498425f">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4md-w8QPpSML3CEGPrIcsg.png" /><figcaption>Fig: Topics created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WCydg-fWkNQoKZEK1rftfQ.png" /><figcaption>Fig: Bronze files with duplicate values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZhgJMWKWZ1CtGndDav5VA.png" /><figcaption>Fig: Building silver Layer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0j6jOMwnAGL4-MM8884wg.png" /><figcaption>Fig: Running quality checks</figcaption></figure><h3>Section 4: Gold Marts</h3><p>In the previous section, we created clean Iceberg silver tables from raw bronze events.</p><p>Silver tables are trusted, typed, deduplicated, and validated. But they are still not the final business layer. Business users usually do not want to join bookings, payments, refunds, inventory, and reviews every time they need a dashboard. They need stable tables that answer clean business questions.</p><p>That is the purpose of the gold layer.</p><p>In this section, we will build five important hospitality data products:</p><ul><li>Revenue mart: “How much revenue do we generate by hotel, room type, channel, and stay date?”</li><li>Occupancy mart: “How many rooms were available, booked, occupied, cancelled, or no-show?”</li><li>Payment reconciliation mart: “Does each booking match payment and refund records?”</li><li>Cancellation mart: “Where are cancellations happening by hotel, room type, channel, and booking date?”</li><li>Demand forecasting feature table: “What clean daily features can be used for demand forecasting?”</li></ul><p>The most important design choice in this section is grain. Each mart has a clear grain:</p><ul><li>Revenue mart: One row per hotel, room type, channel, and stay date.</li><li>Occupancy mart: One row per hotel, room type, and stay date.</li><li>Payment reconciliation mart: One row per booking.</li><li>Cancellation mart: One row per hotel, room type, channel, and booking created date.</li><li>Forecast feature table: One row per hotel, room type, and stay date.</li></ul><p>Clean grain prevents double counting.</p><p>For example, a booking can span multiple nights. If we aggregate booking revenue only by booking creation date, we cannot calculate stay-date revenue correctly. So this section first creates a booking room-night fact table. A three-night booking becomes three rows, one for each stay date.</p><p>The fact table becomes the foundation for revenue, occupancy, and demand features.</p><p>The golden layer is where the raw data finally becomes decision-ready. It is also the layer that will be loaded into Snowflake and visualized in Metabase in the next section.</p><blockquote>To access the code for “Section 4: Gold Marts”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/e2d4aa76372554b48c099fbfca742a04a8da2c40">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xqHd21gWWmPnIyRlo59xg.png" /><figcaption>Fig: Bronze docker compose profile is up and checking silver layer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAjK5nFz43_VjkUAn3mBSA.png" /><figcaption>Fig: Build gold layer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHWDX8FSpybIlIsiEB-CdQ.png" /><figcaption>Fig: Run gold layer quality checks</figcaption></figure><h3>Section 5: Snowflake and Metabase</h3><p>In the previous section, we created Iceberg gold marts from revenue, occupancy, payment reconciliation, cancellations, and demand forecasting features.</p><p>Those gold marts are clean and business-ready. But in many companies, business analytics teams do not query lakehouse tables directly. They usually work with a warehouse and a BI tool. That is the purpose of this section.</p><p>We publish selected gold marts into Snowflake and connect Metabase on top of Snowflake. The lakehouse remains the engineering and reproducibility layer. Snowflake becomes the business analytics serving layer. Metabase becomes the dashboard and exploration layer. This separation is useful.</p><ul><li>The lakehouse is good for raw data, silver cleaning, historical reconstruction, feature tables, and engineering workflows.</li><li>The warehouse is good for analysts who need stable SQL tables, role-based access, fast dashboards, and familiar reporting.</li></ul><p>In this section, we load these gold tables into Snowflake:</p><ul><li>DIM_HOTELS</li><li>DIM_ROOMS</li><li>FACT_BOOKING_ROOM_NIGHT</li><li>MART_REVENUE_DAILY</li><li>MART_OCCUPANCY_DAILY</li><li>MART_PAYMENT_RECONCILIATION</li><li>MART_CANCELLATION_DAILY</li><li>FEATURE_DEMAND_FORECAST_DAILY</li></ul><p>Then we create dashboard queries for:</p><ul><li>revenue by city</li><li>occupancy by hotel</li><li>cancellation rate by channel</li><li>payment reconciliation exceptions</li><li>top hotels by realized revenue</li><li>demand forecasting feature sample</li></ul><p>The goal is not only to show data movement. The goal is to show that the platform ends in usable business outputs.</p><p>A good data engineer should not stop at “the pipeline succeeded.” It should answer whether business users can trust and use the result.</p><blockquote>To access the code for “Section 5: Snowflake and Metabase”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/bce3b1e711d4d1a3470e63e39656f3bb675a5a98">here</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRkAb2MmMUbWqVWS25PXLw.png" /><figcaption>Fig: Bronze docker compose profile is up and checking gold layer quality</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9iY-tBc0vxj5pgq8-T8sg.png" /><figcaption>Fig: After setting up Snowflake credentials, loaded gold layer tables into Snowflake</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fz7S5YglZuYkcPQolysa7g.png" /><figcaption>Fig: Checking snowflake data warehouse</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JqrJXws1A7wWOZ2uuJrnA.png" /><figcaption>Fig: Starting the Docker Compose BI profile, adding Snowflake connection credentials in Metabase, and building the dashboard.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rQ01R66n6yXZdJyF2PGFg.png" /><figcaption>Fig: Metabase Dashboard</figcaption></figure><blockquote>Note 1: This project uses local Metabase for demonstration. In production, <a href="https://medium.com/@thisis-Shitanshu/embedded-bi-for-accounting-7525e075cd0d">Metabase application data should use a production database such as Postgres</a> instead of local embedded storage.</blockquote><blockquote>Note 2: The dashboard uses synthetic demo data generated for pipeline validation, not real production booking volume. The focus is on platform architecture, data modelling, transformation correctness, warehouse serving, and BI readiness.</blockquote><h3>Section 6: MLflow and DVC</h3><ul><li>In Section 4, we created a gold forecasting table for demand forecasting.</li><li>In Section 5, we published the gold marts into Snowflake and connected Metabase for business analytics.</li><li>Now we build the ML layer.</li></ul><p>The goal here is not to create a complex machine learning system. The goal is to show how a data engineering platform can support reliable machine learning. For this project, the business problem is simple:</p><blockquote>Predict next 7-day room-night demand by hotel, room type, and stay date.</blockquote><p>This is useful for a hospitality business because demand forecasting can support pricing, inventory planning, hotel operations, and revenue management.</p><p>The model uses the gold feature table created in Section 4: <strong>stayops.gold.feature_demand_forecast_daily.</strong></p><p>This table already contains clean features such as:</p><ul><li>available rooms</li><li>current room rate</li><li>current demand</li><li>cancellation rate</li><li>average lead time</li><li>review signal</li><li>day of week</li><li>month</li><li>weekend flag</li><li>lagged demand</li><li>rolling demand averages</li><li>next 7-day demand target</li></ul><p>The model is intentionally simple. We train:</p><ol><li>A baseline model</li><li>A RandomForestRegressor model</li></ol><p>The baseline gives us a minimum benchmark. The random forest gives us a stronger non-linear model without requiring deep learning or heavy compute.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4EOCQJgqAOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4EOCQJgqAOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4EOCQJgqAOY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8179e873147de240c1da83d9186e268/href">https://medium.com/media/d8179e873147de240c1da83d9186e268/href</a></iframe><p>Moreover, in our implementation:</p><ul><li>MLflow tracks the experiments. It stores parameters, metrics, model artifacts, and reports.</li><li>DVC tracks the training dataset, test dataset, predictions, reports, and model artifact.</li><li>Git tracks the small .dvc metadata files, while the larger files stay outside normal Git history.</li></ul><p>A drift report compares training and test feature distributions. This is not production monitoring yet, but it shows the right habit:</p><blockquote><strong>A model is not only judged by training metrics. It must also be monitored for changing input data.</strong></blockquote><p>Finishing this section, the project has a complete ML-ready data infrastructure path:</p><pre>Gold feature table<br>-&gt; versioned training dataset<br>-&gt; tracked model experiment<br>-&gt; forecast output table<br>-&gt; drift report</pre><p>This is the point where the data platform becomes useful not only for dashboards, but also for forecasting and decision support.</p><h4>DVC setup</h4><p>DVC should be initialized once in the Git repo.</p><pre>dvc init<br>git add .dvc .dvcignore<br>git commit -m &quot;Initialize DVC&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*mDv6_KPpjQAHwfTjnVHSVQ.png" /><figcaption>Fig: Initialized DVC repository</figcaption></figure><p>For a local remote:</p><pre>mkdir -p ../stayops-dvc-remote<br>dvc remote add -d localremote ../stayops-dvc-remote<br>git add .dvc/config<br>git commit -m &quot;Configure local DVC remote&quot;</pre><p>For S3 later:</p><pre>dvc remote add -d s3remote s3://your-bucket/stayops-dvc</pre><p><a href="https://doc.dvc.org/start">DVC’s docs</a> show that dvc add stores metadata in a small .dvc file while the actual data is kept outside Git, and DVC remotes can use local storage or cloud storage such as Amazon S3.</p><blockquote>Recommended Read: <a href="https://medium.com/@thisis-Shitanshu/implementing-version-control-for-reproducible-machine-learning-projects-a1a6961d84a4">Implementing Version Control for Reproducible Machine Learning Projects</a></blockquote><blockquote>To access the code for “Section 6: MLflow and DVC”, please click <a href="https://github.com/thisis-Shitanshu/stayops-data-platform/commit/91a75ab42bf98edb96b4a997b96314557192e720">here</a>.</blockquote><h4>Implementations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*Nx3nScuGcOQEtS_j_6i8Rw.png" /><figcaption>Fig: Start MLflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUJzx4riJCZnAMXXsYsFvg.png" /><figcaption>Fig: Prepare datasets</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4dmi2k63XWBSXkbmdEWbw.png" /><figcaption>Fig: Train model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODm_O63bxpDlXHaLCSqjuA.png" /><figcaption>Fig: Create predictions and build drift report</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eodrtUn1OCd8_Af6IeILig.png" /><figcaption>Fig: Write forecast output to Iceberg</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPMg9_qKFa_BaCWVf-1J1w.png" /><figcaption>Fig: Open MLflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0O4dc-zeIfbP2EkdYoAnQ.png" /><figcaption>Fig: MLflow run overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqFPwSbkcvMpixZ64XLM0Q.png" /><figcaption>Fig: MLflow run artifacts created</figcaption></figure><p>The important point is this:</p><blockquote>The model trains from the same curated gold feature table that analytics uses. That prevents a common problem where dashboards and ML models use different definitions of demand, cancellation, occupancy, or revenue.</blockquote><h4>DVC tracking flow</h4><p>After generating datasets and model artifacts, run:</p><pre>make dvc-init-local<br>make dvc-track-ml<br>dvc status<br>dvc push<br>git add \<br>  dvc.yaml \<br>  dvc.lock \<br>  data/ml/training/*.dvc \<br>  data/ml/predictions/*.dvc \<br>  data/ml/reports/*.dvc \<br>  models/*.dvc \<br>  .gitignore \<br>  .dvc/config<br>git commit -m &quot;Add DVC-tracked demand forecasting artifacts&quot;</pre><p>Do not commit the actual Parquet or model files. Commit the .dvc files and dvc.lock.</p><h3>Conclusion</h3><p>At this point, StayOps has become a complete hospitality data platform project.</p><p>The platform starts with synthetic operational data for hotels, rooms, bookings, payments, refunds, inventory, guests, and reviews. It turns those records into Kafka events, lands them into a bronze object store, cleans them into Iceberg silver tables, creates business-ready gold marts, publishes selected marts into Snowflake, connects Metabase for dashboards, and builds a demand forecasting workflow with MLflow and DVC.</p><p>The final architecture looks like this:</p><pre>Operational Events<br>→ Kafka<br>→ Bronze object storage<br>→ Spark processing<br>→ Iceberg silver tables<br>→ Iceberg gold marts and feature tables<br>→ Snowflake BA-serving schema<br>→ Metabase dashboards<br>→ MLflow/DVC-backed demand forecasting<br>→ Airflow orchestration, quality checks, runbooks, and cost/security controls</pre><p>The most important part of this project is not the number of tools used. The important part is the flow of business trust.</p><p>Raw data is preserved in bronze. Clean records are created in silver. Business definitions are applied in gold. Analysts consume curated tables through Snowflake and Metabase. The forecasting model trains from the same trusted feature layer instead of a separate private dataset. That is the core engineering idea.</p><p>A hospitality platform needs reliable answers to practical questions:</p><ul><li>How many bookings were created?</li><li>How much revenue was collected?</li><li>Which refunds are pending?</li><li>Which hotels are close to full occupancy?</li><li>Which channels have high cancellation rates?</li><li>Which rooms are likely to see higher demand?</li><li>Which data failed quality checks?</li><li>Which pipeline needs attention?</li></ul><p>StayOps answers these questions through a layered data platform.</p><p>The project can be extended further with Airflow orchestration, cloud deployment, dbt models, streaming quality checks, CI/CD, data contracts, and stronger ML monitoring.</p><p>But even in its current form, it demonstrates the main idea clearly:</p><blockquote>A good data platform does not only move data. It turns operational events into trusted business decisions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RR1PZF3JJHmsnrU2AdEaQQ.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68346d5f58cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded BI for Accounting]]></title>
            <link>https://medium.com/@thisis-Shitanshu/embedded-bi-for-accounting-7525e075cd0d?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/7525e075cd0d</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-superset]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[metabase]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 11:49:47 GMT</pubDate>
            <atom:updated>2026-06-12T11:49:55.499Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Studio (Looker Studio) vs Metabase vs Apache Superset for accounting, compliance, and client-facing business dashboards</h4><p>This tutorial builds one common accounting dataset and then tests it across three dashboard tools:</p><h4><strong>Demo A: Data Studio (Looker Studio)</strong></h4><p>A quick reporting tool for simple dashboards and internal prototypes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIq33rCUSMnM0OMLDce74A.png" /><figcaption>Fig: <a href="https://cloud.google.com/blog/products/data-analytics/looker-studio-is-data-studio">Data Studio</a></figcaption></figure><h4>Demo B: Metabase</h4><p>A business-friendly BI tool that is usually strong for fast embedded dashboard proof of concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8hTIu3IZZGM0P112wII1w.png" /><figcaption>Fig: <a href="https://www.metabase.com/">Metabase</a></figcaption></figure><h4>Demo C: Apache Superset</h4><p>A powerful open-source BI platform for advanced dashboards, customization, and developer-controlled analytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7ElTIC-4-sB0MIGQM4Tgg.png" /><figcaption>Fig: <a href="https://superset.apache.org/">Apache Superset</a></figcaption></figure><p>We are not comparing these tools only by how the charts look. In a real business, the better question is:</p><blockquote><strong>Which tool fits the data, users, app, cost, and long-term engineering needs?</strong></blockquote><p>By the end of this tutorial, we will understand how each tool behaves when the requirement includes:</p><ul><li>Large or growing data</li><li>Flexible dashboards</li><li>Custom visualizations</li><li>Embedded dashboards inside an app</li><li>Client-level filtering</li><li>Cost control</li><li>A setup that can grow beyond a small demo</li></ul><p>Let us start with the industry problem.</p><blockquote>An accounting-led business usually does not need beautiful charts first. It needs trusted numbers.</blockquote><p>That difference matters.</p><p>A dashboard is useful only when the numbers behind it are reliable. If the data is scattered, delayed, duplicated, or incorrectly modeled, then even a beautiful dashboard can create confusion instead of clarity.</p><p>In accounting, the real dashboard problem often looks like this:</p><blockquote>Invoices are in one place. Collections are tracked somewhere else. GST and TDS details may come from separate systems. Compliance tasks may live in spreadsheets. Client-wise risk may be discussed manually in meetings. Some data may come from Tally, Zoho, ERP exports, bank files, Excel sheets, or internal apps.</blockquote><p>This creates a very practical business problem.</p><blockquote>The team does not just need charts. The team needs a trusted reporting layer.</blockquote><p>Here are the common problems we are trying to solve:</p><ol><li><strong>No single source of truth: </strong>One team may track receivables in Excel, another may check GST status separately, and leadership may receive delayed reports. Everyone is looking at data, but not always the same version of truth.</li><li><strong>Delayed visibility: </strong>The accounting team may discover only after month-end that collections are delayed, invoices are overdue, or compliance tasks are pending. By then, the issue has already become a business risk.</li><li><strong>Client-wise reporting pain: </strong>Each client may want a separate view of invoices, collections, outstanding amounts, GST status, or compliance risk. Manually preparing these reports for every client does not scale.</li><li><strong>Risk of wrong numbers: </strong>If duplicate invoices, missing payments, incorrect tax values, or stale exports enter the dashboard, the dashboard becomes dangerous. It may look professional, but the decisions based on it can be wrong.</li><li><strong>Embedding requirement: </strong>Many businesses do not want dashboards only inside a BI tool. They want dashboards inside their own app, client portal, or internal operations system. That means the BI tool must support secure embedding and client-level data isolation.</li></ol><p>So, before choosing Data Studio, Metabase, or Superset, we need to understand the architecture we are building.</p><p>A good accounting dashboard flow usually looks like this:</p><pre>Raw data sources<br>↓<br>Cleaning and validation<br>↓<br>PostgreSQL / BigQuery / ClickHouse / Snowflake<br>↓<br>Modeled reporting views<br>↓<br>BI tool<br>↓<br>Embedded dashboard inside an app</pre><p>This structure is important because the <strong>BI tool should not carry the full burden of fixing messy data</strong>. The BI tool should mainly visualize clean, modeled, and trusted data.</p><p>For this tutorial, we will keep the setup simple. We will create one PostgreSQL database, generate sample accounting data, build reporting views, and then connect the same data to all three tools.</p><blockquote><strong>Note: Every important reporting table should include </strong><strong>client_id. </strong>This is not just a database design detail. It is the foundation for secure client-wise dashboards. When every important table has client_id, we can filter data by client, build client-specific dashboards, and reduce the risk of one client seeing another client’s data.</blockquote><p>We are not just building charts.</p><p>We are building a small embedded BI system that starts from accounting data, creates a trusted reporting layer, compares three BI tools, and shows how dashboards can be placed inside an app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSdpsImAfRFOxH8AQV2bkg.jpeg" /><figcaption>Fig: Comparison of BI Tools</figcaption></figure><h3>Setup</h3><p>Before testing Data Studio, Metabase, and Superset, we need one common data foundation.</p><p>The idea is simple:</p><blockquote>We will create a local project that generates an accounting analytics database in PostgreSQL. The same database will then be connected to three different BI tools. This keeps the comparison fair because every tool will use the same business data.</blockquote><p>Our local stack will have:</p><ul><li><strong>PostgreSQL:</strong> Stores the accounting analytics data</li><li><strong>Adminer:</strong> Lets us inspect the database from the browser</li><li><strong>Metabase:</strong> Builds fast business dashboards and embedded BI POC</li><li><strong>Apache Superset: </strong>Builds advanced open-source BI dashboards</li><li><strong>Flask apps:</strong> Test embedded dashboards inside a simple app page</li></ul><h4>1. Folder structure</h4><p>The project structure is organized by responsibility:</p><pre>mkdir ca-embedded-bi-demo<br>cd ca-embedded-bi-demo<br><br>mkdir -p db/init<br>mkdir -p app<br>mkdir -p looker-studio<br>mkdir -p metabase<br>mkdir -p superset</pre><p>Final structure:</p><pre>ca-embedded-bi-demo/<br>├── docker-compose.yml<br>├── db/<br>│   └── init/<br>│       └── 01_ca_schema_and_seed.sql<br>├── app/<br>│   ├── requirements.txt<br>│   ├── metabase_embed_app.py<br>│   └── superset_embed_app.py<br>├── looker-studio/<br>│   └── embedded_report.html<br>├── metabase/<br>│   └── metabase_questions.sql<br>└── superset/<br>    └── superset_queries.sql<br>    └── superset_config.py</pre><p>Each folder has one job.</p><ul><li>The db/init folder contains the SQL file that creates the accounting schema, inserts sample data, and builds reporting views.</li><li>The app folder contains small Flask apps used to test dashboard embedding.</li><li>The looker-studio folder contains the simple HTML page for testing Data Studio iframe embedding.</li><li>The metabase folder contains SQL questions used to build Metabase charts.</li><li>The superset folder contains Superset-specific setup files, including configuration and chart queries.</li></ul><h4>2. Setting up Superset</h4><p>Create superset/Dockerfile:</p><pre>FROM apache/superset:latest<br><br>USER root<br><br>RUN /app/docker/pip-install.sh psycopg2-binary==2.9.10<br><br>USER superset</pre><p>Create superset/superset_config.py:</p><pre>import os<br><br>SECRET_KEY = os.getenv(&quot;SUPERSET_SECRET_KEY&quot;, &quot;change_this_to_a_long_random_secret&quot;)<br><br>SQLALCHEMY_DATABASE_URI = os.getenv(<br>    &quot;SUPERSET_DATABASE_URI&quot;,<br>    &quot;postgresql+psycopg2://superset:superset_password@superset_db:5432/superset&quot;<br>)<br><br>FEATURE_FLAGS = {<br>    &quot;EMBEDDED_SUPERSET&quot;: True,<br>}<br><br>GUEST_ROLE_NAME = &quot;Gamma&quot;<br><br>TALISMAN_ENABLED = False<br>ENABLE_CORS = True<br>CORS_OPTIONS = {<br>    &quot;supports_credentials&quot;: True,<br>    &quot;allow_headers&quot;: [&quot;*&quot;],<br>    &quot;resources&quot;: [&quot;*&quot;],<br>    &quot;origins&quot;: [&quot;http://localhost:5002&quot;, &quot;http://localhost:8088&quot;],<br>}<br><br>CACHE_CONFIG = {<br>    &quot;CACHE_TYPE&quot;: &quot;RedisCache&quot;,<br>    &quot;CACHE_DEFAULT_TIMEOUT&quot;: 300,<br>    &quot;CACHE_KEY_PREFIX&quot;: &quot;superset_&quot;,<br>    &quot;CACHE_REDIS_HOST&quot;: os.getenv(&quot;REDIS_HOST&quot;, &quot;superset_redis&quot;),<br>    &quot;CACHE_REDIS_PORT&quot;: int(os.getenv(&quot;REDIS_PORT&quot;, &quot;6379&quot;)),<br>    &quot;CACHE_REDIS_DB&quot;: 1,<br>}<br><br>DATA_CACHE_CONFIG = CACHE_CONFIG</pre><p><strong>&gt; Why does Superset need extra setup?</strong></p><p>Metabase is relatively simple to run locally. It mainly needs the Metabase app and its application database. Superset is heavier.</p><p>It needs:</p><ul><li>A metadata database</li><li>A Redis service</li><li>Initialization commands</li><li>A PostgreSQL database driver</li><li>A configuration file</li><li>Feature flags for embedded dashboards</li></ul><p>For this tutorial, Superset is added directly into the same Docker Compose project. This is better than running Superset separately because all services can communicate through the same Docker network.</p><p>One practical benefit is that Superset can connect to the accounting database using the service name: analytics_postgresinstead of using a local machine port.</p><p>This avoids common local port conflicts such as PostgreSQL already using port 5432.</p><h4>3. Creating Docker Compose</h4><p>Create docker-compose.yml:</p><pre>services:<br>  analytics_postgres:<br>    image: postgres:16<br>    container_name: ca_analytics_postgres<br>    restart: unless-stopped<br>    environment:<br>      POSTGRES_USER: ca_user<br>      POSTGRES_PASSWORD: ca_password<br>      POSTGRES_DB: ca_analytics<br>    ports:<br>      - &quot;5433:5432&quot;<br>    volumes:<br>      - ca_analytics_data:/var/lib/postgresql/data<br>      - ./db/init:/docker-entrypoint-initdb.d<br><br>  metabase_appdb:<br>    image: postgres:16<br>    container_name: ca_metabase_appdb<br>    restart: unless-stopped<br>    environment:<br>      POSTGRES_USER: metabase_user<br>      POSTGRES_PASSWORD: metabase_password<br>      POSTGRES_DB: metabaseappdb<br>    volumes:<br>      - ca_metabase_appdb_data:/var/lib/postgresql/data<br><br>  metabase:<br>    image: metabase/metabase:latest<br>    container_name: ca_metabase<br>    restart: unless-stopped<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      MB_DB_TYPE: postgres<br>      MB_DB_DBNAME: metabaseappdb<br>      MB_DB_PORT: 5432<br>      MB_DB_USER: metabase_user<br>      MB_DB_PASS: metabase_password<br>      MB_DB_HOST: metabase_appdb<br>    depends_on:<br>      - analytics_postgres<br>      - metabase_appdb<br><br>  adminer:<br>    image: adminer:latest<br>    container_name: ca_adminer<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8081:8080&quot;<br>    depends_on:<br>      - analytics_postgres<br><br>  superset_db:<br>    image: postgres:16<br>    container_name: ca_superset_db<br>    restart: unless-stopped<br>    environment:<br>      POSTGRES_DB: superset<br>      POSTGRES_USER: superset<br>      POSTGRES_PASSWORD: superset_password<br>    volumes:<br>      - ca_superset_db_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U superset -d superset&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 12<br>    # No host port mapping needed.<br>    # This avoids 5432 conflict.<br><br>  superset_redis:<br>    image: redis:7<br>    container_name: ca_superset_redis<br>    restart: unless-stopped<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 12<br>    # No host port mapping needed.<br><br>  superset:<br>    build:<br>      context: ./superset<br>    image: ca-superset:local<br>    container_name: ca_superset<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8088:8088&quot;<br>    environment:<br>      SUPERSET_SECRET_KEY: &quot;change_this_to_a_long_random_secret&quot;<br>      SUPERSET_CONFIG_PATH: /app/pythonpath/superset_config.py<br>      SUPERSET_DATABASE_URI: postgresql+psycopg2://superset:superset_password@superset_db:5432/superset<br>      REDIS_HOST: superset_redis<br>      REDIS_PORT: 6379<br>    volumes:<br>      - ./superset/superset_config.py:/app/pythonpath/superset_config.py<br>    depends_on:<br>      superset_init:<br>        condition: service_completed_successfully<br><br>  superset_init:<br>    build:<br>      context: ./superset<br>    image: ca-superset:local<br>    container_name: ca_superset_init<br>    environment:<br>      SUPERSET_SECRET_KEY: &quot;change_this_to_a_long_random_secret&quot;<br>      SUPERSET_CONFIG_PATH: /app/pythonpath/superset_config.py<br>      SUPERSET_DATABASE_URI: postgresql+psycopg2://superset:superset_password@superset_db:5432/superset<br>      REDIS_HOST: superset_redis<br>      REDIS_PORT: 6379<br>    volumes:<br>      - ./superset/superset_config.py:/app/pythonpath/superset_config.py<br>    depends_on:<br>      superset_db:<br>        condition: service_healthy<br>      superset_redis:<br>        condition: service_healthy<br>    command:<br>      - /bin/bash<br>      - -c<br>      - |<br>        set -e<br>        superset db upgrade<br>        superset fab create-admin \<br>          --username admin \<br>          --firstname Superset \<br>          --lastname Admin \<br>          --email admin@example.com \<br>          --password admin || true<br>        superset init<br><br>volumes:<br>  ca_analytics_data:<br>  ca_metabase_appdb_data:<br>  ca_superset_db_data:</pre><p><strong>&gt; Why Docker Compose?</strong></p><p>We use Docker Compose because this tutorial needs multiple services working together.</p><p>Instead of installing PostgreSQL, Metabase, Superset, Redis, and Adminer manually, Docker Compose lets us start the full stack with one command.</p><p>This makes the tutorial easier to repeat, easier to debug, and easier to share.</p><p><strong>&gt; Why multiple databases?</strong></p><p>There is one important concept here:</p><blockquote>Business data and BI tool application data are not the same thing.</blockquote><p>So we keep them separate.</p><ul><li>analytics_postgres: Stores accounting business data</li><li>metabase_appdb: Stores Metabase users, dashboards, questions, and settings</li><li>superset_db: Stores Superset users, charts, dashboards, and settings</li></ul><p>This separation is important in real projects.</p><p>Your accounting data should live in a clean analytics database. BI tools should connect to it as consumers. Their internal application data should be stored separately.</p><p>This also helps when backing up systems, upgrading tools, or replacing one BI tool with another.</p><h4>4. Create an Accounting schema and sample data</h4><p>The sample database is intentionally simple, but it represents a real accounting dashboard use case.</p><p>It contains these core tables:</p><ul><li>clients: Client master data</li><li>invoices: Invoice records</li><li>payments: Payment collections against invoices</li><li>gst_filings: GST filing status and tax values</li><li>compliance_tasks: Compliance work and risk status</li></ul><p>These tables are then converted into reporting views.</p><p><strong>The views are more important than the raw tables because BI tools should usually connect to clean, modeled data.</strong></p><ul><li>v_invoice_payment_summary: Invoice-level collection and outstanding details</li><li>v_client_dashboard_summary: Client-level financial summary</li><li>v_compliance_risk_summary: Client-wise compliance risk</li><li>v_monthly_billed_collected: Monthly billing and collection trend</li></ul><p>This is a key habit in BI engineering:</p><blockquote>Do not make every dashboard tool calculate business logic differently. Instead, define the main business logic once in the database, then let BI tools visualize it.</blockquote><p>Create db/init/01_ca_schema_and_seed.sql:</p><pre>CREATE TABLE clients (<br>    client_id INT PRIMARY KEY,<br>    client_name TEXT NOT NULL,<br>    industry TEXT NOT NULL,<br>    city TEXT NOT NULL,<br>    assigned_ca TEXT NOT NULL<br>);<br><br>CREATE TABLE invoices (<br>    invoice_id SERIAL PRIMARY KEY,<br>    client_id INT NOT NULL REFERENCES clients(client_id),<br>    invoice_date DATE NOT NULL,<br>    due_date DATE NOT NULL,<br>    invoice_amount NUMERIC(14,2) NOT NULL,<br>    tax_amount NUMERIC(14,2) NOT NULL,<br>    status TEXT NOT NULL CHECK (status IN (&#39;PAID&#39;, &#39;PARTIAL&#39;, &#39;UNPAID&#39;, &#39;CANCELLED&#39;))<br>);<br><br>CREATE TABLE payments (<br>    payment_id SERIAL PRIMARY KEY,<br>    invoice_id INT NOT NULL REFERENCES invoices(invoice_id),<br>    payment_date DATE NOT NULL,<br>    amount_paid NUMERIC(14,2) NOT NULL<br>);<br><br>CREATE TABLE gst_filings (<br>    filing_id SERIAL PRIMARY KEY,<br>    client_id INT NOT NULL REFERENCES clients(client_id),<br>    return_period DATE NOT NULL,<br>    gstr1_status TEXT NOT NULL CHECK (gstr1_status IN (&#39;FILED&#39;, &#39;PENDING&#39;, &#39;DELAYED&#39;)),<br>    gstr3b_status TEXT NOT NULL CHECK (gstr3b_status IN (&#39;FILED&#39;, &#39;PENDING&#39;, &#39;DELAYED&#39;)),<br>    tax_payable NUMERIC(14,2) NOT NULL,<br>    itc_available NUMERIC(14,2) NOT NULL,<br>    due_date DATE NOT NULL<br>);<br><br>CREATE TABLE compliance_tasks (<br>    task_id SERIAL PRIMARY KEY,<br>    client_id INT NOT NULL REFERENCES clients(client_id),<br>    compliance_type TEXT NOT NULL,<br>    due_date DATE NOT NULL,<br>    status TEXT NOT NULL CHECK (status IN (&#39;DONE&#39;, &#39;PENDING&#39;, &#39;DELAYED&#39;)),<br>    risk_level TEXT NOT NULL CHECK (risk_level IN (&#39;LOW&#39;, &#39;MEDIUM&#39;, &#39;HIGH&#39;))<br>);<br><br>INSERT INTO clients (client_id, client_name, industry, city, assigned_ca) VALUES<br>(101, &#39;Aarav Textiles Pvt Ltd&#39;, &#39;Manufacturing&#39;, &#39;Delhi&#39;, &#39;CA Team A&#39;),<br>(102, &#39;Bhavya Foods LLP&#39;, &#39;FMCG&#39;, &#39;Gurugram&#39;, &#39;CA Team B&#39;),<br>(103, &#39;Chandra Retail Co&#39;, &#39;Retail&#39;, &#39;Noida&#39;, &#39;CA Team A&#39;),<br>(104, &#39;Devika Infra Pvt Ltd&#39;, &#39;Construction&#39;, &#39;Mumbai&#39;, &#39;CA Team C&#39;),<br>(105, &#39;Eshan Digital Services&#39;, &#39;IT Services&#39;, &#39;Bengaluru&#39;, &#39;CA Team B&#39;);<br><br>INSERT INTO invoices (client_id, invoice_date, due_date, invoice_amount, tax_amount, status)<br>SELECT<br>    c.client_id,<br>    DATE &#39;2025-04-01&#39; + (g.i * INTERVAL &#39;7 days&#39;)::INTERVAL,<br>    DATE &#39;2025-04-01&#39; + (g.i * INTERVAL &#39;7 days&#39;)::INTERVAL + INTERVAL &#39;30 days&#39;,<br>    ROUND((50000 + random() * 450000)::numeric, 2),<br>    ROUND((9000 + random() * 81000)::numeric, 2),<br>    CASE<br>        WHEN random() &lt; 0.55 THEN &#39;PAID&#39;<br>        WHEN random() &lt; 0.75 THEN &#39;PARTIAL&#39;<br>        WHEN random() &lt; 0.95 THEN &#39;UNPAID&#39;<br>        ELSE &#39;CANCELLED&#39;<br>    END<br>FROM clients c<br>CROSS JOIN generate_series(0, 52) AS g(i);<br><br>INSERT INTO payments (invoice_id, payment_date, amount_paid)<br>SELECT<br>    invoice_id,<br>    invoice_date + ((10 + random() * 40)::int * INTERVAL &#39;1 day&#39;),<br>    CASE<br>        WHEN status = &#39;PAID&#39; THEN invoice_amount + tax_amount<br>        WHEN status = &#39;PARTIAL&#39; THEN ROUND(((invoice_amount + tax_amount) * (0.25 + random() * 0.50))::numeric, 2)<br>        ELSE 0<br>    END<br>FROM invoices<br>WHERE status IN (&#39;PAID&#39;, &#39;PARTIAL&#39;);<br><br>INSERT INTO gst_filings (<br>    client_id,<br>    return_period,<br>    gstr1_status,<br>    gstr3b_status,<br>    tax_payable,<br>    itc_available,<br>    due_date<br>)<br>SELECT<br>    c.client_id,<br>    DATE &#39;2025-04-01&#39; + (m.i * INTERVAL &#39;1 month&#39;)::INTERVAL,<br>    CASE<br>        WHEN random() &lt; 0.70 THEN &#39;FILED&#39;<br>        WHEN random() &lt; 0.90 THEN &#39;PENDING&#39;<br>        ELSE &#39;DELAYED&#39;<br>    END,<br>    CASE<br>        WHEN random() &lt; 0.68 THEN &#39;FILED&#39;<br>        WHEN random() &lt; 0.90 THEN &#39;PENDING&#39;<br>        ELSE &#39;DELAYED&#39;<br>    END,<br>    ROUND((25000 + random() * 250000)::numeric, 2),<br>    ROUND((10000 + random() * 180000)::numeric, 2),<br>    DATE &#39;2025-04-20&#39; + (m.i * INTERVAL &#39;1 month&#39;)::INTERVAL<br>FROM clients c<br>CROSS JOIN generate_series(0, 13) AS m(i);<br><br>INSERT INTO compliance_tasks (<br>    client_id,<br>    compliance_type,<br>    due_date,<br>    status,<br>    risk_level<br>)<br>SELECT<br>    c.client_id,<br>    task_type,<br>    DATE &#39;2025-04-01&#39; + ((random() * 420)::int * INTERVAL &#39;1 day&#39;),<br>    CASE<br>        WHEN random() &lt; 0.65 THEN &#39;DONE&#39;<br>        WHEN random() &lt; 0.88 THEN &#39;PENDING&#39;<br>        ELSE &#39;DELAYED&#39;<br>    END,<br>    CASE<br>        WHEN random() &lt; 0.50 THEN &#39;LOW&#39;<br>        WHEN random() &lt; 0.82 THEN &#39;MEDIUM&#39;<br>        ELSE &#39;HIGH&#39;<br>    END<br>FROM clients c<br>CROSS JOIN (<br>    VALUES<br>    (&#39;GST Return&#39;),<br>    (&#39;TDS Return&#39;),<br>    (&#39;ROC Filing&#39;),<br>    (&#39;Advance Tax&#39;),<br>    (&#39;Invoice Reconciliation&#39;),<br>    (&#39;Bank Reconciliation&#39;)<br>) AS t(task_type)<br>CROSS JOIN generate_series(1, 8);<br><br>CREATE VIEW v_invoice_payment_summary AS<br>SELECT<br>    i.invoice_id,<br>    i.client_id,<br>    c.client_name,<br>    c.industry,<br>    c.city,<br>    i.invoice_date,<br>    i.due_date,<br>    i.invoice_amount,<br>    i.tax_amount,<br>    i.invoice_amount + i.tax_amount AS gross_invoice_amount,<br>    COALESCE(SUM(p.amount_paid), 0) AS amount_collected,<br>    (i.invoice_amount + i.tax_amount) - COALESCE(SUM(p.amount_paid), 0) AS outstanding_amount,<br>    i.status,<br>    CASE<br>        WHEN i.due_date &lt; CURRENT_DATE<br>             AND (i.invoice_amount + i.tax_amount) - COALESCE(SUM(p.amount_paid), 0) &gt; 0<br>        THEN &#39;OVERDUE&#39;<br>        ELSE &#39;NOT_OVERDUE&#39;<br>    END AS overdue_status<br>FROM invoices i<br>JOIN clients c ON c.client_id = i.client_id<br>LEFT JOIN payments p ON p.invoice_id = i.invoice_id<br>GROUP BY<br>    i.invoice_id,<br>    i.client_id,<br>    c.client_name,<br>    c.industry,<br>    c.city,<br>    i.invoice_date,<br>    i.due_date,<br>    i.invoice_amount,<br>    i.tax_amount,<br>    i.status;<br><br>CREATE VIEW v_client_dashboard_summary AS<br>SELECT<br>    client_id,<br>    client_name,<br>    industry,<br>    city,<br>    COUNT(invoice_id) AS invoice_count,<br>    ROUND(SUM(gross_invoice_amount), 2) AS total_billed,<br>    ROUND(SUM(amount_collected), 2) AS total_collected,<br>    ROUND(SUM(outstanding_amount), 2) AS total_outstanding,<br>    ROUND(SUM(CASE WHEN overdue_status = &#39;OVERDUE&#39; THEN outstanding_amount ELSE 0 END), 2) AS overdue_outstanding,<br>    ROUND(<br>        CASE<br>            WHEN SUM(gross_invoice_amount) = 0 THEN 0<br>            ELSE SUM(amount_collected) * 100.0 / SUM(gross_invoice_amount)<br>        END,<br>        2<br>    ) AS collection_efficiency_pct<br>FROM v_invoice_payment_summary<br>GROUP BY client_id, client_name, industry, city;<br><br>CREATE VIEW v_compliance_risk_summary AS<br>SELECT<br>    c.client_id,<br>    c.client_name,<br>    COUNT(*) AS total_tasks,<br>    COUNT(*) FILTER (WHERE ct.status = &#39;DONE&#39;) AS completed_tasks,<br>    COUNT(*) FILTER (WHERE ct.status = &#39;PENDING&#39;) AS pending_tasks,<br>    COUNT(*) FILTER (WHERE ct.status = &#39;DELAYED&#39;) AS delayed_tasks,<br>    COUNT(*) FILTER (WHERE ct.risk_level = &#39;HIGH&#39;) AS high_risk_tasks<br>FROM clients c<br>JOIN compliance_tasks ct ON ct.client_id = c.client_id<br>GROUP BY c.client_id, c.client_name;<br><br>CREATE VIEW v_monthly_billed_collected AS<br>SELECT<br>    DATE_TRUNC(&#39;month&#39;, invoice_date)::date AS month,<br>    ROUND(SUM(gross_invoice_amount), 2) AS billed_amount,<br>    ROUND(SUM(amount_collected), 2) AS collected_amount,<br>    ROUND(SUM(outstanding_amount), 2) AS outstanding_amount<br>FROM v_invoice_payment_summary<br>GROUP BY DATE_TRUNC(&#39;month&#39;, invoice_date)::date<br>ORDER BY month;</pre><p><strong>&gt; Why </strong><strong>client_id matters</strong></p><p>Every important table and reporting view should include client_id.</p><p>This is not just for filtering. It is the foundation for client-level security.</p><p>When dashboards are embedded inside an app, the app may need to show only one client’s data. If every reporting view has client_id, we can safely apply filters such as: client_id = 101</p><p><strong>This becomes important later when we test Metabase locked parameters and Superset guest token row-level security.</strong></p><h4>5. Start the local stack</h4><p>After creating the project files, start the local stack:</p><pre>docker compose up -d</pre><p>Then check that containers are running:</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXtwCzMd5DFQwvWOmU91OA.png" /><figcaption>Fig: Running docker compose</figcaption></figure><p>At this point, the main services should be available at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4o1kMj6ULKQTbseFsTapQ.png" /><figcaption>Fig: Starting Metabase</figcaption></figure><ul><li>Metabase: <a href="http://localhost:3000/">http://localhost:3000</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrZ_B8UYxY1YX9DglEKCEg.png" /><figcaption>Fig: Starting Adminer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjnGgVxku0uiyyjWp46rDQ.png" /><figcaption>Fig: Adminer, after Login</figcaption></figure><ul><li>Adminer: <a href="http://localhost:8081/">http://localhost:8081</a></li></ul><p>Adminer is useful for checking whether the database was created correctly. Use it to connect to the accounting database:</p><pre>System: PostgreSQL<br>Server: analytics_postgres<br>Username: ca_user<br>Password: ca_password<br>Database: ca_analytics</pre><p>And Superset at <a href="http://localhost:8088/">http://localhost:8088</a>.</p><p>Once this works, the foundation is ready. We now have:</p><ul><li>One accounting analytics database</li><li>Clean reporting views</li><li>Metabase running locally</li><li>Superset running locally</li><li>Adminer available for inspection</li><li>A structure ready for embedded dashboard apps</li></ul><p>From here, we can start testing each BI tool one by one.</p><h3>Demo A: Data Studio</h3><h4>Goal</h4><p>In this demo, we will build a quick accounting dashboard using exported CSV data. The goal is not to build the most advanced dashboard. The goal is to understand where Looker Studio fits.</p><p>Data Studio is usually the easiest tool to start with. It is useful when the team wants a fast dashboard from CSV files, Google Sheets, or BigQuery-backed tables.</p><p>For this tutorial, we will use it to answer one simple question:</p><blockquote><strong>Can Data Studio work for a quick accounting dashboard, and is it suitable for embedding inside a client-facing app?</strong></blockquote><p><strong>&gt; What we will build</strong></p><p>We will use two reporting views from PostgreSQL:</p><ul><li><strong>Client dashboard summary</strong>: Client-wise billed, collected, outstanding, and overdue values</li><li><strong>Monthly billed vs collected</strong>: Month-wise billing and collection trend</li></ul><p>These are exported from PostgreSQL into CSV files and uploaded into Data Studio.</p><p>This is a good beginner-friendly workflow because it avoids API setup, drivers, and database connection issues. But it also shows an important limitation: <strong>CSV upload is useful for demos, not for serious high-volume production dashboards.</strong></p><h4>Step 1: Export the dashboard view to CSV</h4><p>At this stage, our PostgreSQL database already contains clean reporting views.</p><p>We export two views:</p><ul><li>client_dashboard_summary.csv: v_client_dashboard_summary</li><li>monthly_billed_collected.csv: v_monthly_billed_collected</li></ul><pre>docker exec -i ca_analytics_postgres psql \<br>  -U ca_user \<br>  -d ca_analytics \<br>  -c &quot;\copy (SELECT * FROM v_client_dashboard_summary) TO STDOUT WITH CSV HEADER&quot; \<br>  &gt; ./looker-studio/client_dashboard_summary.csv</pre><p>The first file gives us client-level numbers.</p><pre>docker exec -i ca_analytics_postgres psql \<br>  -U ca_user \<br>  -d ca_analytics \<br>  -c &quot;\copy (SELECT * FROM v_monthly_billed_collected) TO STDOUT WITH CSV HEADER&quot; \<br>  &gt; ./looker-studio/monthly_billed_collected.csv</pre><p>The second file gives us monthly trend data.</p><p>This separation is intentional. Client summary data and monthly trend data have different shapes, so they should be treated as separate data sources in Data Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-YvJ8B6JCUUkIMMfUX2iQ.png" /><figcaption>Fig: Exporting PostgreSQL views to CSV</figcaption></figure><h4>Step 2: Upload CSV files to Data Studio</h4><p>Open Data Studio and create a new report.</p><p>Then add both CSV files as data sources.</p><p>The flow is:</p><ol><li>Create a new report.</li><li>Add data.</li><li>Choose CSV upload.</li><li>Upload client_dashboard_summary.csv.</li><li>Add monthly_billed_collected.csv as another data source.</li></ol><p>However, this is also where we should pause and understand the tradeoff.</p><p><strong>CSV upload is good for:</strong></p><ul><li>quick demos</li><li>small datasets</li><li>internal reporting</li><li>one-time analysis</li><li>early dashboard prototypes</li></ul><p><strong>CSV upload is weak for:</strong></p><ul><li>large daily data</li><li>automated refresh</li><li>multi-client reporting</li><li>production-grade embedded analytics</li><li>strict data quality and security workflows</li></ul><p>Data Studio has CSV upload limits, so <strong>for serious dashboards the better path is usually a database-backed source such as BigQuery</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9ZXuTqAsRAbV_CEqlqrsQ.png" /><figcaption>Fig: Starting a Data Studio report</figcaption></figure><blockquote>Google’s docs say a file-upload dataset is a group of files with the same structure, and every file added to a dataset must have exactly the same fields in the same order. New files are appended, not merged. Duplicate rows are not automatically removed.</blockquote><h4>Step 3: Build the dashboard charts</h4><p>Create these charts:</p><ol><li>Scorecard: SUM(total_billed)</li><li>Scorecard: SUM(total_collected)</li><li>Scorecard: SUM(total_outstanding)</li><li>Scorecard: SUM(overdue_outstanding)</li><li>Bar chart: client_name vs total_outstanding</li><li>Table: client_name, collection_efficiency_pct, overdue_outstanding</li><li>Time series from monthly data: month, billed_amount, collected_amount</li></ol><p>This gives us a simple accounting dashboard that answers basic business questions:</p><ul><li>How much did we bill?</li><li>How much did we collect?</li><li>How much is still outstanding?</li><li>Which clients have higher overdue amounts?</li><li>Are collections keeping pace with billing?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ytnOZeXKBwhWxXHEuwkiw.png" /><figcaption>Fig: Completing the Data Studio dashboard</figcaption></figure><blockquote>If Data Studio does not allow direct type conversion, create a new calculated field.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcI2KykAVNBTpCVhVrkKQQ.jpeg" /><figcaption>Fig: Data Studio Dashboard Sample</figcaption></figure><h4>Step 4: Test embedding</h4><p>After the report is ready, use the sharing option in Data Studio to get the embed URL. Then place that embed URL inside a simple HTML page.</p><p>Create looker-studio/embedded_report.html:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;CA Dashboard: Data Studio Embed&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      font-family: Arial, sans-serif;<br>      margin: 0;<br>      background: #f6f7f9;<br>    }<br><br>    header {<br>      padding: 16px 24px;<br>      background: #ffffff;<br>      border-bottom: 1px solid #ddd;<br>    }<br><br>    main {<br>      padding: 24px;<br>    }<br><br>    iframe {<br>      width: 100%;<br>      height: 800px;<br>      border: 1px solid #ddd;<br>      background: white;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;header&gt;<br>    &lt;h2&gt;CA Client Dashboard&lt;/h2&gt;<br>    &lt;p&gt;Data Studio embedded report demo&lt;/p&gt;<br>  &lt;/header&gt;<br><br>  &lt;main&gt;<br>    &lt;iframe<br>      src=&quot;PASTE_LOOKER_STUDIO_EMBED_URL_HERE (FIND IT IN SHARE)&quot;<br>      allowfullscreen&gt;<br>    &lt;/iframe&gt;<br>  &lt;/main&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open the looker-studio/embedded_report.html in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dPC09WdLrgKfdgPECxvaQ.png" /><figcaption>Fig: Testing Data Studio embedding</figcaption></figure><p>The purpose of this step is not to build a full app. The purpose is to test how the dashboard behaves when placed inside an app-like page.</p><p>This is where Data Studio’s limitations become visible. For internal reporting, the embed experience may be good enough. For client-facing dashboards, we need to be more careful.</p><p>Private embedded reports can require Google login. Embedded reports may also include Data Studio branding or watermark behavior. Manual refresh behavior is limited compared with a fully controlled embedded BI flow.</p><h4>Demo A conclusion</h4><p>Data Studio is good when the requirement is:</p><ul><li>quick prototype</li><li>internal reporting</li><li>Google Sheets or BigQuery-based reporting</li><li>low engineering setup</li><li>simple business dashboards</li></ul><p>It is weaker when the requirement is:</p><ul><li>white-labeled app embedding</li><li>private client-facing dashboards</li><li>high customization</li><li>multi-tenant embedded analytics</li><li>large CSV-based workflows</li><li>deep control over dashboard behavior</li></ul><p>So the practical conclusion is:</p><blockquote><strong>Use Data Studio when speed matters more than control.</strong></blockquote><p>It is a strong starting point for internal dashboards and early prototypes. But when the requirement becomes secure embedded BI inside a client portal, we should evaluate Metabase or Superset more seriously.</p><h3>Demo B: Metabase</h3><h4>Goal</h4><p>In this demo, we will build an embedded dashboard that can show one client’s financial view. This is where the tutorial becomes more realistic.</p><p>Looker Studio helped us build a quick dashboard, but now we want something closer to a client-facing BI experience. The dashboard should not just be visible inside an app. It should also be filtered for the correct client.</p><p>That means client 101 should see only client 101 data. Client 102 should see only client 102 data. This is where Metabase becomes useful.</p><p>Metabase is usually a strong first proof of concept when the requirement is:</p><ul><li>fast setup</li><li>business-friendly dashboards</li><li>cost-effective implementation</li><li>simple embedded BI</li><li>client-level filtering with locked parameters</li></ul><p>The main idea is simple:</p><pre>PostgreSQL reporting views<br>        ↓<br>Metabase saved questions<br>        ↓<br>Metabase dashboard<br>        ↓<br>Signed embed URL<br>        ↓<br>Dashboard inside app</pre><h4>Step 1: Open Metabase and connect to the database</h4><p>Metabase runs locally at:</p><pre>http://localhost:3000</pre><p>After opening Metabase, create the admin account and connect it to the accounting analytics database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4ROWzz7Yezf3YrVTyLW9A.png" /><figcaption>Fig: Setting up Metabase Admin</figcaption></figure><p>To add the database, use the following:</p><pre>Database type: PostgreSQL<br>Name: ca_analytics<br>Host: analytics_postgres<br>Port: 5432<br>Database name: ca_analytics<br>Username: ca_user<br>Password: ca_password</pre><h4>Step 2: Create saved questions</h4><p>In Metabase, a “question” is a saved query or visual exploration.</p><p>For this dashboard, we create questions from the reporting views that already exist in PostgreSQL.</p><ul><li>Client financial summary, v_client_dashboard_summary: Client-level billed, collected, outstanding, and overdue values</li><li>Monthly billed vs collected, v_monthly_billed_collected: Month-wise billing and collection trend</li><li>Compliance risk, v_compliance_risk_summary: Pending, delayed, and high-risk compliance work</li><li>Client invoice detail, v_invoice_payment_summary: Invoice-level drill-down for one client</li></ul><p>This is a good BI pattern.</p><blockquote>The database handles the business logic. Metabase handles the dashboard experience.</blockquote><p>That means Metabase is not responsible for calculating every accounting rule from raw tables. It consumes clean reporting views and turns them into charts, tables, filters, and dashboards.</p><p>Create metabase/metabase_questions.sql:</p><pre>-- Question 1: Client financial summary<br>SELECT<br>    client_id,<br>    client_name,<br>    industry,<br>    city,<br>    invoice_count,<br>    total_billed,<br>    total_collected,<br>    total_outstanding,<br>    overdue_outstanding,<br>    collection_efficiency_pct<br>FROM v_client_dashboard_summary<br>ORDER BY overdue_outstanding DESC;<br><br>-- Question 2: Monthly billed vs collected<br>SELECT<br>    month,<br>    billed_amount,<br>    collected_amount,<br>    outstanding_amount<br>FROM v_monthly_billed_collected<br>ORDER BY month;<br><br>-- Question 3: Compliance risk<br>SELECT<br>    client_id,<br>    client_name,<br>    total_tasks,<br>    completed_tasks,<br>    pending_tasks,<br>    delayed_tasks,<br>    high_risk_tasks<br>FROM v_compliance_risk_summary<br>ORDER BY high_risk_tasks DESC, delayed_tasks DESC;<br><br>-- Question 4: Client-specific invoice detail. Default Client ID: 101. Set Variable type to Number.<br>SELECT<br>    invoice_id,<br>    client_id,<br>    client_name,<br>    invoice_date,<br>    due_date,<br>    gross_invoice_amount,<br>    amount_collected,<br>    outstanding_amount,<br>    overdue_status<br>FROM v_invoice_payment_summary<br>[[WHERE client_id = {{client_id}}]]<br>ORDER BY due_date DESC;</pre><p>In Metabase:</p><ol><li>Go to New.</li><li>Choose SQL Query.</li><li>Select ca_analytics.</li><li>Paste each query.</li><li>Save each as a question.</li><li>Build a dashboard called: <strong>CA Client Financial Control Tower</strong></li></ol><p>Recommended dashboard cards:</p><ul><li><strong>Total billed</strong>: Overall billing value</li><li><strong>Total collected</strong>: Total amount collected</li><li><strong>Total outstanding</strong>: Pending receivable amount</li><li><strong>Overdue outstanding</strong>: Risk-focused receivable value</li><li><strong>Monthly billed vs collected</strong>: Trend view</li><li><strong>Client-wise outstanding</strong>: Compare clients</li><li><strong>Compliance risk</strong>: Operational risk view</li><li><strong>Invoice details</strong>: Drill-down table</li></ul><p>For a client-facing embedded dashboard, the most important part is the client_id filter.</p><p>The invoice detail question should support a client_id variable. In Metabase, set this variable as a <strong>Number</strong>, not text.</p><p>This avoids common SQL errors when filtering an integer column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HC9pPwllL42xgIX-IgszA.png" /><figcaption>Fig: Completing the Metabase dashboard</figcaption></figure><h4>Step 3: Enable embedding</h4><p>Next, enable embedding in Metabase. The flow is:</p><pre>Admin settings <br>↓ <br>Settings <br>↓ <br>Embedding <br>↓ <br>Enable embedding <br>↓ <br>Copy secret key</pre><p>The secret key is used by the backend app to generate a signed embed URL. This is important.</p><p>The frontend should not create the signed URL directly. The secret key should stay on the server side.</p><p>The app backend signs a short-lived token, adds the dashboard ID, adds the locked parameters, and returns the final embed URL.</p><p><strong>&gt; Use locked parameters</strong></p><p>Locked parameters are the key part of this demo. They allow the backend to say:</p><p><em>Show this dashboard, but lock it to </em><em>client_id = 101.</em></p><p>So even if the viewer changes something in the browser, the dashboard should remain restricted to the client ID included in the signed token.</p><p>This is the basic idea behind client-specific embedded dashboards.</p><p>This is why we designed the reporting views with client_id from the beginning. If a chart does not have client_id, it cannot be safely filtered for a specific client.</p><h4>Step 4: Create a small embedding app</h4><p>To test embedding, we create a small Flask app.</p><p>The app does three things:</p><ol><li>Accepts a selected client_id</li><li>Creates a signed Metabase embed URL on the backend</li><li>Shows the dashboard inside an iframe</li></ol><p>Create app/requirements.txt:</p><pre>Flask==3.0.3<br>PyJWT==2.8.0<br>requests==2.32.3</pre><p>Install dependencies:</p><pre>cd app<br>python3 -m venv .venv<br>source .venv/bin/activate<br>pip install -r requirements.txt</pre><p>Create app/metabase_embed_app.py:</p><pre>import os<br>import time<br>import jwt<br>from flask import Flask, render_template_string, request<br><br>app = Flask(__name__)<br><br>METABASE_SITE_URL = os.getenv(&quot;METABASE_SITE_URL&quot;, &quot;http://localhost:3000&quot;)<br>METABASE_SECRET_KEY = os.getenv(&quot;METABASE_SECRET_KEY&quot;, &quot;PASTE_METABASE_EMBED_SECRET_HERE&quot;)<br>METABASE_DASHBOARD_ID = int(os.getenv(&quot;METABASE_DASHBOARD_ID&quot;, &quot;2&quot;))<br><br>HTML_TEMPLATE = &quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;CA Dashboard: Metabase Embed&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            margin: 0;<br>            font-family: Arial, sans-serif;<br>            background: #f6f7f9;<br>        }<br><br>        header {<br>            padding: 16px 24px;<br>            background: white;<br>            border-bottom: 1px solid #ddd;<br>        }<br><br>        main {<br>            padding: 24px;<br>        }<br><br>        .client-switcher {<br>            margin-bottom: 16px;<br>            padding: 12px;<br>            background: white;<br>            border: 1px solid #ddd;<br>        }<br><br>        iframe {<br>            width: 100%;<br>            height: 850px;<br>            border: 1px solid #ddd;<br>            background: white;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;header&gt;<br>        &lt;h2&gt;CA Client Dashboard&lt;/h2&gt;<br>        &lt;p&gt;Metabase embedded dashboard demo with client-level filtering&lt;/p&gt;<br>    &lt;/header&gt;<br><br>    &lt;main&gt;<br>        &lt;div class=&quot;client-switcher&quot;&gt;<br>            &lt;form method=&quot;GET&quot;&gt;<br>                &lt;label for=&quot;client_id&quot;&gt;Client ID:&lt;/label&gt;<br>                &lt;select name=&quot;client_id&quot; id=&quot;client_id&quot;&gt;<br>                    &lt;option value=&quot;101&quot; {% if client_id == 101 %}selected{% endif %}&gt;101&lt;/option&gt;<br>                    &lt;option value=&quot;102&quot; {% if client_id == 102 %}selected{% endif %}&gt;102&lt;/option&gt;<br>                    &lt;option value=&quot;103&quot; {% if client_id == 103 %}selected{% endif %}&gt;103&lt;/option&gt;<br>                    &lt;option value=&quot;104&quot; {% if client_id == 104 %}selected{% endif %}&gt;104&lt;/option&gt;<br>                    &lt;option value=&quot;105&quot; {% if client_id == 105 %}selected{% endif %}&gt;105&lt;/option&gt;<br>                &lt;/select&gt;<br>                &lt;button type=&quot;submit&quot;&gt;View dashboard&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br><br>        &lt;iframe src=&quot;{{ iframe_url }}&quot; frameborder=&quot;0&quot; allowtransparency&gt;&lt;/iframe&gt;<br>    &lt;/main&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;<br><br>def build_metabase_embed_url(https://medium.com/client_id:%20int) -&gt; str:<br>    payload = {<br>        &quot;resource&quot;: {&quot;dashboard&quot;: METABASE_DASHBOARD_ID},<br>        &quot;params&quot;: {&quot;client_id&quot;: client_id},<br>        &quot;exp&quot;: round(time.time()) + 60 * 10<br>    }<br><br>    token = jwt.encode(payload, METABASE_SECRET_KEY, algorithm=&quot;HS256&quot;)<br><br>    return (<br>        f&quot;{METABASE_SITE_URL}/embed/dashboard/{token}&quot;<br>        f&quot;#bordered=true&amp;titled=true&quot;<br>    )<br><br>@app.route(&quot;/&quot;)<br>def index():<br>    client_id = int(request.args.get(&quot;client_id&quot;, &quot;101&quot;))<br>    iframe_url = build_metabase_embed_url(https://medium.com/client_id)<br><br>    return render_template_string(<br>        HTML_TEMPLATE,<br>        iframe_url=iframe_url,<br>        client_id=client_id<br>    )<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=5001, debug=True)</pre><p>Run:</p><pre>export METABASE_SITE_URL=&quot;http://localhost:3000&quot;<br>export METABASE_SECRET_KEY=&quot;PASTE_METABASE_EMBED_SECRET_HERE&quot;<br>export METABASE_DASHBOARD_ID=&quot;PASTE_DASHBOARD_ID_HERE&quot;<br>python metabase_embed_app.py</pre><p>The app runs locally at:</p><pre>http://localhost:5001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GqhcUiKOzhtwKKWx9cQjpg.png" /><figcaption>Fig: Testing Metabase dashboard embedding</figcaption></figure><p>In the browser, we can switch between clients and confirm that the embedded dashboard changes based on the selected client_id.</p><p>This is not a production client portal. It is a simple proof of concept.</p><p>But it proves the core workflow:</p><pre>User selects client<br>        ↓<br>Backend signs Metabase token<br>        ↓<br>Token includes locked client_id<br>        ↓<br>Dashboard loads inside app<br>        ↓<br>Viewer sees only relevant data</pre><h4>Important production notes</h4><p>For a real accounting or client portal, the proof of concept needs stronger production controls.</p><p>At minimum:</p><ul><li>Do not expose database credentials to the frontend.</li><li>Do not expose the Metabase embedding secret.</li><li>Use HTTPS.</li><li>Use read-only database users.</li><li>Keep client_id or tenant_id in every reporting view.</li><li>Use locked parameters or row-level permissions carefully.</li><li>Keep the Metabase application database separate from the business analytics database.</li><li>Avoid using one shared public dashboard for sensitive client data.</li><li>Monitor dashboard usage and slow queries.</li></ul><p>The local demo is meant to teach the architecture. A production system needs proper security, access control, backups, and monitoring.</p><h4>Demo B conclusion</h4><p>Metabase is strong when the goal is to build the first embedded BI proof of concept quickly.</p><p>It is useful for:</p><ul><li>business-friendly dashboards</li><li>fast implementation</li><li>SQL-based reporting</li><li>basic embedded analytics</li><li>client-specific dashboards using locked parameters</li><li>low setup complexity compared with heavier BI platforms</li></ul><p>It becomes weaker when the requirement is:</p><ul><li>highly custom visualizations</li><li>advanced white-labeling</li><li>very custom BI user experience</li><li>complex open-source-only multi-tenant security</li><li>deep frontend control over every dashboard interaction</li></ul><p>The practical conclusion is:</p><blockquote><strong>Use Metabase when you want to prove the embedded BI workflow quickly.</strong></blockquote><p>It is often the <strong>best middle path between a simple dashboard tool and a fully engineered BI platform</strong>.</p><h3>Demo C: Apache Superset</h3><h4>Goal</h4><p>In this demo, we will build the same accounting dashboard in Apache Superset. This time, the focus is not only speed. The focus is flexibility.</p><p>Superset is a better fit when the long-term requirement includes:</p><ul><li>advanced customization</li><li>large database support</li><li>SQL-first analytics</li><li>custom visualizations</li><li>developer-controlled embedded BI</li><li>more control over dashboard behavior</li></ul><p>Compared with Looker Studio and Metabase, Superset feels more like a BI platform that engineering teams can extend and operate. That power also comes with more setup responsibility.</p><p><strong>&gt; Why Superset?</strong></p><p>Superset is an open-source data exploration and visualization platform.</p><p>It supports no-code chart building, SQL Lab, dashboard filters, many SQL databases, caching, Jinja templating, CSS customization, semantic-layer concepts, and custom visualization plugins.</p><p>For a simple internal dashboard, this may feel heavy. But for a long-term embedded BI platform, this flexibility can be useful.</p><p>The main architecture looks like this:</p><pre>PostgreSQL reporting views<br>        ↓<br>Superset datasets<br>        ↓<br>Superset charts<br>        ↓<br>Superset dashboard<br>        ↓<br>Guest token embedding<br>        ↓<br>Client portal / app</pre><h4>Step 1: Open Superset</h4><p>Superset runs locally at:</p><pre>http://localhost:8088</pre><p>For this local demo, we use the admin account created during setup.</p><pre>username: admin<br>password: admin</pre><blockquote>For production, do not keep default secrets. Superset’s Kubernetes docs explicitly say default security settings, and passwords must be updated for production, and a strong SECRET_KEY should be generated.</blockquote><h4>Step 2: Connect Superset to the accounting database</h4><p>In Superset, go to:</p><pre>Settings → Database Connections → + Database</pre><p>Because Superset is running inside the same Docker Compose project, it should connect to the accounting PostgreSQL database using the Docker service name: analytics_postgres not localhost.</p><pre>Host: analytics_postgres<br>Port: 5432<br>Database: ca_analytics<br>Username: ca_user<br>Password: ca_password</pre><p>This is the same idea we used with Metabase.</p><p>The BI tool runs as a container, so it connects to the database container through the Docker network.</p><h4>Step 3: Create Superset datasets</h4><p>In Superset, charts are created from datasets. A dataset can be based on a physical table, a database view, or a SQL query.</p><p>For this demo, we create datasets from our reporting views:</p><ul><li>v_client_dashboard_summary: Client-level financial summary</li><li>v_invoice_payment_summary: Invoice-level drill-down</li><li>v_compliance_risk_summary: Compliance risk by client</li><li>v_monthly_billed_collected: Monthly billed vs collected trend</li></ul><p>This is an important difference from writing raw queries inside every chart. The dataset becomes a reusable analytics object. Multiple charts can be built from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTBzikpMDJkrLJWCNj5AKA.png" /><figcaption>Fig: Created Superset dataset</figcaption></figure><h4>Step 4: Create Superset charts</h4><p>Now create charts from the datasets.</p><p>Create superset/superset_queries.sql:</p><pre>-- Superset dataset: Client dashboard summary<br>SELECT<br>    client_id,<br>    client_name,<br>    industry,<br>    city,<br>    invoice_count,<br>    total_billed,<br>    total_collected,<br>    total_outstanding,<br>    overdue_outstanding,<br>    collection_efficiency_pct<br>FROM v_client_dashboard_summary;<br><br>-- Superset dataset: Monthly billed collected<br>SELECT<br>    month,<br>    billed_amount,<br>    collected_amount,<br>    outstanding_amount<br>FROM v_monthly_billed_collected;<br><br>-- Superset dataset: Compliance risk<br>SELECT<br>    client_id,<br>    client_name,<br>    total_tasks,<br>    completed_tasks,<br>    pending_tasks,<br>    delayed_tasks,<br>    high_risk_tasks<br>FROM v_compliance_risk_summary;<br><br>-- Superset dataset: Invoice-level detail<br>SELECT<br>    invoice_id,<br>    client_id,<br>    client_name,<br>    invoice_date,<br>    due_date,<br>    gross_invoice_amount,<br>    amount_collected,<br>    outstanding_amount,<br>    overdue_status<br>FROM v_invoice_payment_summary;</pre><p>Build these charts:</p><ul><li>Big Number: total_billed</li><li>Big Number: total_collected</li><li>Big Number: total_outstanding</li><li>Big Number: overdue_outstanding</li><li>Bar Chart: client_name vs overdue_outstanding</li><li>Line Chart: month vs billed_amount and collected_amount</li><li>Table: client_name, delayed_tasks, high_risk_tasks</li><li>Table: invoice-level outstanding details</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbdAY_HgbJXpCt_pPJ3lqw.png" /><figcaption>Fig: Superset Charts created using Datasets</figcaption></figure><p>This dashboard gives both a financial view and an operational risk view.</p><p>Create a dashboard named: <strong>CA Operations and Compliance Control Tower</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXMF7UpstEVD6T1r2LF3Rg.png" /><figcaption>Fig: Superset dashboard created</figcaption></figure><p><strong>&gt; Important lesson: every client-filtered chart needs </strong><strong>client_id</strong></p><p>This is one of the most important engineering lessons in the Superset demo. When we embed a dashboard for one client, we may apply a row-level security clause like: client_id = 101</p><p>This works only if the dataset behind the chart has a client_id column.</p><p>If the monthly chart is based on a view that does not contain client_id, Superset cannot apply the client filter. The chart may fail with an error like:</p><pre>column &quot;client_id&quot; does not exist</pre><p>The fix is to create a client-wise monthly view, for example:</p><pre>v_monthly_billed_collected_by_client</pre><p>That view should include:</p><pre>client_id<br>client_name<br>month<br>billed_amount<br>collected_amount<br>outstanding_amount</pre><p><strong>This is why data modeling matters.</strong></p><blockquote>Embedding is not only a frontend problem. It starts in the database design.</blockquote><h4>Step 5: Enable embedded dashboard mode</h4><p>Superset embedding requires embedded dashboard support to be enabled in configuration. For the local proof of concept, the setup enables:</p><pre>FEATURE_FLAGS = {<br>    &quot;EMBEDDED_SUPERSET&quot;: True<br>}<br><br>GUEST_ROLE_NAME = &quot;Gamma&quot;<br><br>TALISMAN_ENABLED = False<br>ENABLE_CORS = True</pre><p>This makes it possible to embed the dashboard inside a local Flask app.</p><blockquote>For production, this must be handled carefully. Security settings should not be relaxed casually. CORS should be restricted to trusted domains. HTTPS should be enabled. Guest access should be limited. Row-level security should be tested properly.</blockquote><h4>Step 6: Create a guest token embedding app</h4><p>Superset embedding works differently from Metabase.</p><p>In Metabase, we created a signed iframe URL. In Superset, the recommended embedded flow uses a guest token.</p><p>The app does this:</p><pre>App backend logs into Superset<br>        ↓<br>Backend requests a guest token<br>        ↓<br>Guest token includes dashboard access<br>        ↓<br>Guest token includes row-level security clause<br>        ↓<br>Frontend embeds dashboard using Superset embedded SDK</pre><p>Create app/superset_embed_app.py:</p><pre>import os<br>import requests<br>from flask import Flask, jsonify, render_template_string, request<br><br>app = Flask(__name__)<br><br>SUPERSET_URL = os.getenv(&quot;SUPERSET_URL&quot;, &quot;http://localhost:8088&quot;)<br>SUPERSET_USERNAME = os.getenv(&quot;SUPERSET_USERNAME&quot;, &quot;admin&quot;)<br>SUPERSET_PASSWORD = os.getenv(&quot;SUPERSET_PASSWORD&quot;, &quot;admin&quot;)<br>SUPERSET_DASHBOARD_UUID = os.getenv(&quot;SUPERSET_DASHBOARD_UUID&quot;, &quot;PASTE_DASHBOARD_UUID_HERE&quot;)<br><br>HTML_TEMPLATE = &quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;CA Dashboard: Superset Embed&lt;/title&gt;<br>    &lt;script src=&quot;https://unpkg.com/@superset-ui/embedded-sdk&quot;&gt;&lt;/script&gt;<br>    &lt;style&gt;<br>        body {<br>            margin: 0;<br>            font-family: Arial, sans-serif;<br>            background: #f6f7f9;<br>        }<br><br>        header {<br>            padding: 16px 24px;<br>            background: white;<br>            border-bottom: 1px solid #ddd;<br>        }<br><br>        main {<br>            padding: 24px;<br>        }<br><br>        .client-switcher {<br>            margin-bottom: 16px;<br>            padding: 12px;<br>            background: white;<br>            border: 1px solid #ddd;<br>        }<br><br>        #dashboard-container {<br>            width: 100%;<br>            height: 850px;<br>            background: white;<br>            border: 1px solid #ddd;<br>        }<br><br>        #dashboard-container iframe {<br>            width: 100%;<br>            height: 850px;<br>            border: none;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;header&gt;<br>        &lt;h2&gt;CA Client Dashboard&lt;/h2&gt;<br>        &lt;p&gt;Superset embedded dashboard demo with guest token flow&lt;/p&gt;<br>    &lt;/header&gt;<br><br>    &lt;main&gt;<br>        &lt;div class=&quot;client-switcher&quot;&gt;<br>            &lt;form method=&quot;GET&quot;&gt;<br>                &lt;label for=&quot;client_id&quot;&gt;Client ID:&lt;/label&gt;<br>                &lt;select name=&quot;client_id&quot; id=&quot;client_id&quot;&gt;<br>                    &lt;option value=&quot;101&quot; {% if client_id == 101 %}selected{% endif %}&gt;101&lt;/option&gt;<br>                    &lt;option value=&quot;102&quot; {% if client_id == 102 %}selected{% endif %}&gt;102&lt;/option&gt;<br>                    &lt;option value=&quot;103&quot; {% if client_id == 103 %}selected{% endif %}&gt;103&lt;/option&gt;<br>                    &lt;option value=&quot;104&quot; {% if client_id == 104 %}selected{% endif %}&gt;104&lt;/option&gt;<br>                    &lt;option value=&quot;105&quot; {% if client_id == 105 %}selected{% endif %}&gt;105&lt;/option&gt;<br>                &lt;/select&gt;<br>                &lt;button type=&quot;submit&quot;&gt;View dashboard&lt;/button&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br><br>        &lt;div id=&quot;dashboard-container&quot;&gt;&lt;/div&gt;<br>    &lt;/main&gt;<br><br>    &lt;script&gt;<br>        async function fetchGuestToken() {<br>            const response = await fetch(&quot;/guest-token?client_id={{ client_id }}&quot;);<br>            const data = await response.json();<br>            if (!response.ok) {<br>                throw new Error(data.error || &quot;Failed to fetch Superset guest token&quot;);<br>            }<br>            return data.token;<br>        }<br><br>        supersetEmbeddedSdk.embedDashboard({<br>            id: &quot;{{ dashboard_uuid }}&quot;,<br>            supersetDomain: &quot;{{ superset_url }}&quot;,<br>            mountPoint: document.getElementById(&quot;dashboard-container&quot;),<br>            fetchGuestToken: fetchGuestToken,<br>            dashboardUiConfig: {<br>                hideTitle: false,<br>                hideChartControls: false,<br>                filters: {<br>                    expanded: true<br>                }<br>            }<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;<br><br>def parse_response(response):<br>    try:<br>        body = response.json()<br>    except ValueError:<br>        body = {&quot;message&quot;: response.text}<br><br>    if not response.ok:<br>        message = body.get(&quot;message&quot;, body)<br>        raise RuntimeError(<br>            f&quot;Superset API returned {response.status_code} for {response.url}: {message}&quot;<br>        )<br><br>    return body<br><br>def get_access_token(session: requests.Session):<br>    login_url = f&quot;{SUPERSET_URL}/api/v1/security/login&quot;<br><br>    payload = {<br>        &quot;username&quot;: SUPERSET_USERNAME,<br>        &quot;password&quot;: SUPERSET_PASSWORD,<br>        &quot;provider&quot;: &quot;db&quot;,<br>        &quot;refresh&quot;: True<br>    }<br><br>    response = session.post(login_url, json=payload, timeout=20)<br>    body = parse_response(response)<br><br>    return body[&quot;access_token&quot;]<br><br>def get_csrf_token(session: requests.Session, access_token: str):<br>    csrf_url = f&quot;{SUPERSET_URL}/api/v1/security/csrf_token/&quot;<br>    response = session.get(<br>        csrf_url,<br>        headers={&quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;},<br>        timeout=20<br>    )<br>    body = parse_response(response)<br><br>    return body[&quot;result&quot;]<br><br>def get_guest_token(client_id: int):<br>    session = requests.Session()<br>    access_token = get_access_token(session)<br>    csrf_token = get_csrf_token(session, access_token)<br><br>    guest_token_url = f&quot;{SUPERSET_URL}/api/v1/security/guest_token/&quot;<br><br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;Referer&quot;: SUPERSET_URL,<br>        &quot;X-CSRFToken&quot;: csrf_token<br>    }<br><br>    payload = {<br>        &quot;user&quot;: {<br>            &quot;username&quot;: f&quot;client_{client_id}&quot;,<br>            &quot;first_name&quot;: &quot;Client&quot;,<br>            &quot;last_name&quot;: str(client_id)<br>        },<br>        &quot;resources&quot;: [<br>            {<br>                &quot;type&quot;: &quot;dashboard&quot;,<br>                &quot;id&quot;: SUPERSET_DASHBOARD_UUID<br>            }<br>        ],<br>        &quot;rls&quot;: [<br>            {<br>                &quot;clause&quot;: f&quot;client_id = {client_id}&quot;<br>            }<br>        ]<br>    }<br><br>    response = session.post(<br>        guest_token_url,<br>        headers=headers,<br>        json=payload,<br>        timeout=20<br>    )<br><br>    body = parse_response(response)<br><br>    return body[&quot;token&quot;]<br><br>@app.route(&quot;/&quot;)<br>def index():<br>    client_id = int(request.args.get(&quot;client_id&quot;, &quot;101&quot;))<br><br>    return render_template_string(<br>        HTML_TEMPLATE,<br>        client_id=client_id,<br>        dashboard_uuid=SUPERSET_DASHBOARD_UUID,<br>        superset_url=SUPERSET_URL<br>    )<br><br>@app.route(&quot;/guest-token&quot;)<br>def guest_token():<br>    client_id = int(request.args.get(&quot;client_id&quot;, &quot;101&quot;))<br>    try:<br>        token = get_guest_token(client_id)<br>    except Exception as exc:<br>        app.logger.exception(&quot;Failed to create Superset guest token&quot;)<br>        return jsonify({&quot;error&quot;: str(exc)}), 502<br><br>    return {&quot;token&quot;: token}<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=5002, debug=True)</pre><p>Run:</p><pre>cd app<br>source .venv/bin/activate<br><br>export SUPERSET_URL=&quot;http://localhost:8088&quot;<br>export SUPERSET_USERNAME=&quot;admin&quot;<br>export SUPERSET_PASSWORD=&quot;admin&quot;<br>export SUPERSET_DASHBOARD_UUID=&quot;PASTE_DASHBOARD_UUID_HERE&quot;<br><br>python superset_embed_app.py</pre><p>The local app runs at:</p><pre><a href="http://localhost:5002/">http://localhost:5002</a></pre><p>The app lets us select a client ID and then loads the Superset dashboard for that client. This is more engineering-heavy than Metabase, but it also gives more control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aclD4LSW_5-Kq-DsAbAIXA.png" /><figcaption>Fig: Testing Superset embedding</figcaption></figure><h4>Important Superset production notes</h4><p>For production Superset, the local demo setup is not enough.</p><p>A production deployment should include:</p><ul><li>strong SECRET_KEY</li><li>secure admin credentials</li><li>HTTPS</li><li>proper metadata database</li><li>Redis and Celery where needed</li><li>caching for expensive dashboards</li><li>read-only database users</li><li>restricted CORS origins</li><li>tested row-level security</li><li>monitoring for query performance</li><li>backups for Superset metadata</li><li>no admin credentials inside frontend code</li></ul><p>Superset gives more control, but the team must also operate it responsibly.</p><h4>Demo C conclusion</h4><p>Superset is strong when the requirement is:</p><ul><li>advanced open-source BI</li><li>long-term BI platform architecture</li><li>SQL-first analytics</li><li>custom visualization needs</li><li>developer-controlled embedded BI</li><li>complex dashboard behavior</li><li>stronger control over the analytics layer</li></ul><p>It is weaker when the requirement is:</p><ul><li>very fast non-technical setup</li><li>simple dashboards needed immediately</li><li>small teams without DevOps support</li><li>minimum engineering maintenance</li></ul><p>The practical conclusion is:</p><blockquote><strong>Use Superset when control matters more than simplicity.</strong></blockquote><p>It is not the fastest path for a basic dashboard, but it is a strong path when the goal is to build a flexible, open-source BI platform that can grow with the product.</p><h3>Clean Up</h3><p>After finishing the demos, you can stop the local stack.</p><p>For normal cleanup, use:</p><pre>docker compose down</pre><p>This stops and removes the running containers, but keeps the database volumes. Use this when you may want to restart the project later without losing data.</p><p>If you want to remove everything created by this demo, including database volumes and locally built images, use:</p><pre>docker compose down --volumes --rmi all --remove-orphans</pre><p>Be careful with this command. It removes:</p><ul><li><strong>Containers</strong>: Stops and removes running services</li><li><strong>Volumes</strong>: Deletes stored PostgreSQL, Metabase, and Superset data</li><li><strong>Images</strong>: Removes locally built images</li><li><strong>Orphans</strong>: Removes old containers not present in the current Compose file</li></ul><p>Use the full cleanup command only when you are sure you no longer need the local demo data.</p><p>In most cases, this is enough:</p><pre>docker compose down</pre><p>The stronger cleanup command is useful when you want a completely fresh start.</p><h3>Conclusion</h3><p>For a CA-style business dashboard, the best BI tool depends on the stage of the project. There is no single winner for every situation.</p><p>The right question is not: <strong>Which BI tool is best?</strong></p><p>The better question is: <strong>What does the business need right now, and what will the system need later?</strong></p><p>If the goal is a quick internal dashboard, <strong>Data Studio / Looker Studio</strong> is a good starting point. It is simple, fast, and easy to use for early reporting. But when the requirement becomes private client-facing embedding, white-labeling, or deeper control, its limitations become important.</p><p>If the goal is the first embedded BI proof of concept, <strong>Metabase + PostgreSQL</strong> is usually the most practical path. It is fast to set up, business-friendly, and good enough to test whether embedded dashboards actually solve the client reporting problem.</p><p>If the goal is a long-term open-source BI platform, <strong>Apache Superset + a production analytics database</strong> is the stronger architecture. It gives more control, more customization, and better room for advanced BI workflows. But it also needs more engineering, stronger DevOps, and careful security setup.</p><p>In this tutorial, we built one accounting analytics database and tested it across three tools.</p><p>We created:</p><ul><li>a local PostgreSQL analytics database</li><li>accounting tables for clients, invoices, payments, GST filings, and compliance tasks</li><li>reporting views for dashboards</li><li>a quick Data Studio dashboard</li><li>a Metabase embedded BI proof of concept</li><li>a Superset dashboard with guest-token embedding</li><li>a simple app-style flow for client-specific dashboards</li></ul><p>The most important lesson is this:</p><blockquote><strong>Embedded BI is not only about charts. It is about data modeling, access control, app integration, and trust.</strong></blockquote><p>A dashboard is useful only when the data is clean, the business logic is consistent, and the right user sees the right data.</p><p>From here, this project can be extended further.</p><p>You can add real ERP data, Tally exports, Zoho data, GST return data, bank statement reconciliation, role-based access, automated refresh, audit logs, row-level security, and production deployment on cloud infrastructure.</p><p>That is how a simple dashboard demo slowly becomes a real analytics product. Happy engineering!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U94YJIduyhaq1u8XBV_E6A.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7525e075cd0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MinIO and AIStor Object Storage]]></title>
            <link>https://medium.com/@thisis-Shitanshu/minio-and-aistor-object-storage-10acb6dac40d?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/10acb6dac40d</guid>
            <category><![CDATA[minio]]></category>
            <category><![CDATA[object-storage]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Tue, 19 May 2026 12:46:14 GMT</pubDate>
            <atom:updated>2026-05-19T12:46:14.488Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical, updated guide for engineers to understand object storage, MinIO’s shift to AIStor, S3-compatible APIs, use cases, and hands-on Python code.</h4><p>Modern applications do not only store small files in folders. They store images, logs, videos, backups, AI datasets, model checkpoints, telemetry, transaction records, security events, and lakehouse tables. As systems grow, the old “file server and folder” mindset becomes difficult to scale.</p><p>This is where <strong>object storage</strong> becomes important.</p><p>Object storage stores data as independent objects. Each object has data, a name, and metadata. Applications access these objects through APIs, most commonly through S3-compatible APIs.</p><p>MinIO became popular because it gave engineers a high-performance, S3-compatible object store that could run locally, on servers, on Kubernetes, and in cloud-like environments.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLFOIsHSSYIK37B3VtACkNksUw8_puUuAC&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLFOIsHSSYIK37B3VtACkNksUw8_puUuAC&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgY090GEDdu8%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLBqShW3fRcQ6No1aqIkh2dKoiRWgQ%26days_since_epoch%3D20594&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5651b84987efecb52037c47aa56c0f/href">https://medium.com/media/2a5651b84987efecb52037c47aa56c0f/href</a></iframe><p>The basic concepts from the MinIO developer playlist are still useful: objects are BLOBs, buckets hold objects, prefixes organize objects inside buckets, and applications usually use object storage through RESTful S3 APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaHQq8-APPc4KnHKQCG3oA.png" /><figcaption>Fig: <a href="https://github.com/minio/minio">https://github.com/minio/minio</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5YyE_tdpwNYOgDTQXft9g.png" /><figcaption>Fig: <a href="https://www.min.io/download">https://www.min.io/download</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1Wbr9DgBmODsRIu3MGeXw.png" /><figcaption>Fig: <a href="https://www.min.io/pricing">https://www.min.io/pricing</a></figcaption></figure><p>But the MinIO ecosystem has changed. The old minio/minio GitHub repository now states that it is no longer maintained and points users toward <strong>AIStor Free</strong> and <strong>AIStor Enterprise</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQVezIVFtmcPJfigKvzZxw.png" /><figcaption>Fig: <a href="https://docs.min.io/aistor/">MinIO AIStor Documentation</a></figcaption></figure><p>The current AIStor documentation describes AIStor as an exascale AI data store with native support for S3 APIs for objects, Iceberg for tables, and SFTP for files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3igETUQ67UE-JsbEttVmIQ.png" /><figcaption>Fig: <a href="https://www.min.io/">https://www.min.io</a></figcaption></figure><h3>What changed in MinIO?</h3><p>Before we learn the fundamentals, we need to clear up the current naming and setup confusion.</p><p>The older references often use:</p><pre>docker run minio/minio</pre><p>That was fine for many older MinIO workflows. But today, this should not be the main recommendation for new projects because the minio/minio GitHub repository says it is no longer maintained and lists <strong>AIStor Free</strong> and <strong>AIStor Enterprise</strong> as alternatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVgenp4ZaG433y53kXjrXQ.png" /><figcaption>Fig: <a href="https://hub.docker.com/r/minio/minio">https://hub.docker.com/r/minio/minio</a></figcaption></figure><p>The Docker Hub page for minio/minio still describes MinIO as high-performance, S3-compatible object storage under AGPLv3, but the image page is marked archived.</p><p>The current practical split is:</p><ul><li><strong>AIStor Free: </strong>Full-featured, single-node deployment for developers, researchers, enthusiasts, small organizations, and standalone usage.</li><li><strong>AIStor Enterprise Lite:</strong> Multi-node architecture for smaller teams with capacity below 400 TiB.</li><li><strong>AIStor Enterprise:</strong> Multi-node enterprise deployment with premium support.</li><li><a href="https://github.com/minio/minio#source-only-distribution"><strong>MinIO Community source:</strong></a> Community edition distributed as source code, not the old prebuilt binary-first workflow.</li></ul><p>AIStor Free is listed as free of charge, full-featured, and single-node. It includes self-service community, Slack, and documentation support. AIStor container deployment requires a license file, and the documentation says users can request a Free Tier license for a single compute resource with one or more drives.</p><p>We will use <strong>AIStor Free</strong>! 🚀</p><h3>What is an object?</h3><p>An <strong>object</strong> is a stored unit of data.</p><p>In simple form:</p><pre>object = data + object name + metadata</pre><p>Examples of objects:</p><pre>invoice.pdf<br>profile-photo.png<br>raw/transactions/2026/05/18/file-001.csv<br>models/fraud-detection/v1/model.pkl<br>checkpoints/run-42/epoch-10.pt<br>logs/app/2026/05/18/server.log</pre><p>An object can be small or large. It can be a document, image, video, backup, model file, Parquet file, CSV file, JSON document, log file, or binary artifact.</p><p>AIStor documentation describes an object as binary data, such as images, audio files, spreadsheets, or executable code. It also notes that object storage platforms provide tools for storing, listing, and retrieving objects through S3-compatible APIs.</p><p>An object usually has:</p><ol><li><strong>Data:</strong> The actual bytes.</li><li><strong>Object name:</strong> The unique key inside the bucket.</li><li><strong>Metadata: </strong>System and custom information about the object.</li><li><strong>ETag:</strong> An identifier often used to compare object content.</li><li><strong>Version ID:</strong> Available when versioning is enabled.</li><li><strong>Retention data:</strong> Available when object lock is enabled.</li></ol><blockquote><strong>Object storage</strong> is not mainly about editing one line inside a file. It <strong>is about storing, retrieving, copying, listing, protecting, versioning, and deleting whole objects through APIs.</strong></blockquote><h3>3. What is a bucket?</h3><p>A <strong>bucket</strong> is a top-level container for objects.</p><p>Example:</p><pre>Bucket: ml-artifacts<br>Objects:<br>  raw/images/img-001.jpg<br>  raw/images/img-002.jpg<br>  checkpoints/run-1/epoch-10.pt<br>  models/fraud/v1/model.pkl</pre><p>A bucket usually represents an application, product, environment, team, domain, or dataset.</p><p>Examples:</p><pre>dev<br>ml-artifacts<br>raw-telemetry<br>financial-transactions<br>security-lake<br>model-checkpoints<br>customer-documents</pre><p>Buckets can have their own:</p><ul><li>access policies</li><li>versioning</li><li>object locking</li><li>lifecycle rules</li><li>replication rules</li><li>event notifications</li><li>encryption settings</li><li>quotas</li></ul><blockquote>Junior engineers often ask: “Should my application create buckets dynamically?”</blockquote><blockquote>Usually, no. In most production systems, buckets are created and configured by the platform, infrastructure, or storage administration team. They usually define bucket policies, encryption, versioning, lifecycle rules, replication, object locking, and access permissions before the application starts using the bucket.</blockquote><blockquote>The application should normally consume the assigned bucket and perform object-level operations such as put, get, list, copy, and delete.</blockquote><blockquote>The exception is when you are building a storage platform, tenant-provisioning system, data platform control plane, or Storage-as-a-Service product. In those cases, bucket creation may be part of the application’s responsibility, but it should still be controlled through strict policies, validation, naming rules, quotas, audit logs, and least-privilege permissions.</blockquote><h3>What is a prefix?</h3><p>A <strong>prefix</strong> is the folder-like part of an object name.</p><p>Object stores do not usually store folders the same way a traditional file system does. Instead, they use object names that contain slashes.</p><p>Example:</p><pre>raw/transactions/2026/05/18/file-001.csv</pre><p>Here:</p><pre>Bucket: financial-data<br>Object name: raw/transactions/2026/05/18/file-001.csv<br>Prefix: raw/transactions/2026/05/18/</pre><p>Prefixes help organize objects inside a bucket.</p><p>Good prefix examples:</p><pre>raw/<br>curated/<br>features/<br>models/<br>checkpoints/<br>logs/<br>reports/<br>tmp/<br>archive/</pre><p><strong>A practical AI bucket layout can look like this:</strong></p><pre>ml-artifacts/<br>  raw/<br>    images/<br>    text/<br>    audio/<br>  labels/<br>  features/<br>  training/<br>  validation/<br>  checkpoints/<br>  models/<br>  metrics/</pre><blockquote>A prefix exists only when objects exist under that prefix. <strong>If all objects under a prefix are deleted, the prefix disappears.</strong> Prefixes are just used to <strong>logically separate data inside a bucket</strong> and are part of the object name.</blockquote><h3>What is object storage?</h3><p><strong>Object storage</strong> is a storage architecture designed for large amounts of unstructured and semi-structured data.</p><p>It is commonly used for:</p><pre>AI datasets<br>model checkpoints<br>data lake files<br>application uploads<br>logs<br>metrics<br>traces<br>backups<br>videos<br>images<br>documents<br>security events<br>financial records<br>IoT and sensor data</pre><p>A simple object storage flow looks like this:</p><pre>Application<br>    |<br>    | PUT object<br>    v<br>Object Store Bucket<br>    |<br>    | GET object<br>    v<br>Application</pre><p>Object storage is popular because it gives engineers:</p><ul><li>HTTP API access</li><li>high scalability</li><li>separation of storage and compute</li><li>metadata support</li><li>policy-based access control</li><li>durability features</li><li>tool ecosystem compatibility</li></ul><blockquote><a href="https://docs.min.io/aistor/developers/s3-api-compatibility/">AIStor’s S3 API compatibility page documents</a> object APIs such as PutObject, GetObject, HeadObject, ListObjects, CopyObject, DeleteObject, and DeleteObjects.</blockquote><h3>What is S3-compatible storage?</h3><p>S3-compatible storage means your application can use S3-style APIs and tools to read and write objects.</p><p>This matters because many engineering tools already understand S3-like storage:</p><pre>Apache Spark<br>Trino<br>Presto<br>DuckDB<br>MLflow<br>Ray<br>Kafka connectors<br>Grafana Loki<br>Velero<br>Airflow S3 hooks<br>PyTorch data pipelines<br>data lakehouse engines<br>backup tools</pre><p>The practical benefit is portability.</p><p>You can write code like this:</p><pre>Application code -&gt; S3-compatible API -&gt; Object store</pre><p>Then point the application to different backends by changing the configuration:</p><ul><li>local AIStor</li><li>production AIStor</li><li>AWS S3</li><li>another S3-compatible system</li></ul><blockquote><a href="https://docs.min.io/aistor/developers/">AIStor’s developer documentation</a> says that existing S3 applications can typically work with AIStor with minimal configuration changes, usually by changing the endpoint URL and credentials.</blockquote><h3>What is AIStor?</h3><p><strong>AIStor</strong> is MinIO’s current high-performance data store for AI and analytics workloads.</p><p>The current AIStor documentation describes it as an exascale AI data store that supports:</p><ul><li>S3 API for objects</li><li>Iceberg for tables</li><li>SFTP for files</li></ul><p>It is licensed under the <a href="https://docs.min.io/license/">MinIO Software License</a>.</p><p>In simple language:</p><p>AIStor = object storage + table storage direction + file access direction + enterprise operations</p><p>For developers, the most important part is still the S3-compatible object API. That is what your Python, Java, Go, .NET, Spark, MLflow, and lakehouse tools commonly use.</p><p>For platform engineers, the broader value is that AIStor can become a central storage layer for AI, analytics, observability, security, transaction analytics, and industrial data workloads.</p><h3>AIStor Free versus Enterprise</h3><p>For learning and standalone use, <strong>AIStor Free</strong> is the right path.</p><p>AIStor Free is described as a full-featured single-node deployment for developers, researchers, enthusiasts, small organizations, and anyone comfortable with standalone deployment. It is free of charge and uses self-service community Slack and documentation support.</p><p>For production deployments that need multi-node scale, high availability, support, diagnostics, governance, and SLAs, MinIO positions Enterprise Lite and Enterprise as the commercial options.</p><p>Use this simple decision table:</p><ul><li>Learning object storage -&gt; AIStor Free</li><li>Local development -&gt; AIStor Free</li><li>Homelab or small standalone deployment -&gt; AIStor Free</li><li>Production without a distributed HA requirement -&gt; AIStor Free may be technically enough, but check the license and risk</li><li>Multi-node production -&gt; AIStor Enterprise Lite or Enterprise</li><li>Regulated enterprise workload -&gt; AIStor Enterprise</li><li>Old tutorial compatibility -&gt; Understand minio/minio, but do not make it your main new setup</li></ul><h3>Important concepts before setup</h3><p>AIStor exposes two main interfaces:</p><ol><li>S3 API endpoint: used by applications and SDKs</li><li>Console endpoint: used by humans through the browser</li></ol><p>In the current AIStor container documentation, the default local ports are:</p><ul><li>S3 API: 9000</li><li>Console: 9001</li></ul><p>The documentation also shows the default local login as:</p><ul><li>Username: minioadmin</li><li>Password: minioadmin</li></ul><blockquote>This is acceptable for local learning only. In production, never use default credentials. The <a href="https://docs.min.io/aistor/installation/container/install/">AIStor container documentation</a> shows the container running on ports 9000 and 9001, and the console available on the port 9001.</blockquote><h3>Hands-on setup: AIStor Free with Docker</h3><p>This setup is for local learning.</p><p>It will create:</p><ol><li>AIStor Server container</li><li>local object storage data directory</li><li>AIStor Client mc</li><li>dev bucket</li><li>ml-artifacts bucket</li><li>devuser application user</li><li>read/write policy for devuser</li><li>Python object operations</li></ol><h4>I. Prerequisites</h4><p>You need:</p><pre>Docker<br>Python 3.9 or newer<br>pip<br>AIStor Free license file</pre><p>AIStor requires a license file to run. The official container setup says you can request an <a href="https://docs.min.io/aistor/operations/licenses/">AIStor Free Tier license</a> and save it as minio.license.</p><p>Create the working directory:</p><pre>mkdir -p $HOME/Projects/aistor-demo/data<br>mkdir -p $HOME/Projects/aistor-demo/certs<br>mkdir -p $HOME/Projects/aistor-demo/sample_data<br>mkdir -p $HOME/Projects/aistor-demo/downloads<br>cd $HOME/Projects/aistor-demo</pre><p>Place your downloaded license here:</p><pre>$HOME/Projects/aistor-demo/minio.license</pre><p>Your folder should look like this:</p><pre>aistor-demo/<br>  data/<br>  certs/<br>  sample_data/<br>  downloads/<br>  minio.license</pre><h4>II. Start AIStor Server</h4><p>Run:</p><pre>docker pull quay.io/minio/aistor/minio:latest<br><br>docker run -dt \<br>  -p 9000:9000 \<br>  -p 9001:9001 \<br>  -v $HOME/Projects/aistor-demo/data:/mnt/data \<br>  -v $HOME/Projects/aistor-demo/minio.license:/minio.license \<br>  -v $HOME/Projects/aistor-demo/certs:/etc/minio/certs \<br>  --name aistor-server \<br>  quay.io/minio/aistor/minio:latest minio server /mnt/data \<br>  --license /minio.license</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LT_oydZO4oTDWixODnRIJw.png" /><figcaption>Fig: Output #1</figcaption></figure><p>Check logs:</p><pre>docker logs aistor-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-R3s9tysq8ul4LL-ehVISQ.png" /><figcaption>Fig: Output #2</figcaption></figure><p>Open the Console: <a href="http://localhost:9001/">http://localhost:9001</a></p><p>Login for local learning:</p><ul><li>Username: minioadmin</li><li>Password: minioadmin</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifFyJlo5_tQaqXAE0W8BbQ.png" /><figcaption>Fig: Output #3</figcaption></figure><h4>III. Install AIStor Client mc, <strong>Client command-line tool</strong>.</h4><p>The official AIStor docs describe mc as the AIStor Client and show it being installed separately from the AIStor Server. It is used to connect to S3-compatible services and run operations against them.</p><ul><li>AIStor Server = the object storage server</li><li>mc = the terminal tool used to manage and test that server</li></ul><p>First check your CPU architecture:</p><pre>uname -m</pre><p>If it shows x86_64, use AMD64:</p><pre># downloads the mc binary<br>curl --progress-bar -L https://dl.min.io/aistor/mc/release/linux-amd64/mc -o mc<br># makes it executable<br>chmod +x ./mc<br># installs it into your system PATH<br>sudo mv ./mc /usr/local/bin/<br># confirms installation<br>mc --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*Vv5vkfuOCiqPKU3KjbFtxQ.png" /><figcaption>Output #4</figcaption></figure><p>If it shows aarch64 or arm64, use ARM64:</p><pre># downloads the mc binary<br>curl --progress-bar -L https://dl.min.io/aistor/mc/release/linux-arm64/mc -o mc<br># makes it executable<br>chmod +x ./mc<br># installs it into your system PATH<br>sudo mv ./mc /usr/local/bin/<br># confirms installation<br>mc --version</pre><h4>IV. Configure local alias</h4><p>After that, you connect mc to your local AIStor server:</p><pre>mc alias set aistor http://localhost:9000 minioadmin minioadmin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*otdNyA5ksXdvwGDpVqJHjA.png" /><figcaption>Fig: Output #5</figcaption></figure><p>This creates a shortcut named aistor for your server. The official syntax is:</p><pre>mc alias set ALIAS URL ACCESSKEY SECRETKEY</pre><p>Next, Create buckets:</p><pre>mc mb --ignore-existing aistor/dev<br>mc mb --ignore-existing aistor/ml-artifacts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*J6vk86k864dETgkHcZ4e6w.png" /><figcaption>Fig: Output #6</figcaption></figure><p>Create an application user:</p><pre>mc admin user add aistor devuser devpass123</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*sB1CH_vu9MuL5eeX8xDpjw.png" /><figcaption>Fig: Output #7</figcaption></figure><p>Create a policy file: ./dev-readwrite.json</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetBucketLocation&quot;,<br>        &quot;s3:ListBucket&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::dev&quot;,<br>        &quot;arn:aws:s3:::ml-artifacts&quot;<br>      ]<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetObject&quot;,<br>        &quot;s3:PutObject&quot;,<br>        &quot;s3:DeleteObject&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::dev/*&quot;,<br>        &quot;arn:aws:s3:::ml-artifacts/*&quot;<br>      ]<br>    }<br>  ]<br>}</pre><blockquote><a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html">AWS documentation</a> says 2012-10-17 is the current policy language version and recommends always setting the Version element to 2012-10-17.</blockquote><p>Create and attach the policy:</p><pre>mc admin policy create aistor dev-readwrite dev-readwrite.json<br>mc admin policy attach aistor dev-readwrite --user devuser</pre><p>Confirm:</p><pre>mc admin user info aistor devuser</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*ybVX7aJtiMurkXA3liQy_A.png" /><figcaption>Fig: Output #8</figcaption></figure><blockquote>AIStor’s CLI documentation includes mc mb for bucket creation, mc admin user add for users, and mc admin policy create plus mc admin policy attach for policy management. New users have no default policies until policies are attached.</blockquote><h3>Python setup</h3><p>Create a virtual environment:</p><pre>python3 -m venv .venv<br>source .venv/bin/activate<br><br>pip install minio</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fa-2_b8S3TL39RFgb7l5jw.png" /><figcaption>Fig: Output #9</figcaption></figure><p>The current Python SDK uses:</p><pre>from minio import Minio</pre><p>The Minio constructor accepts endpoint, access key, secret key, secure flag, region, session token, custom HTTP client, and credentials provider.</p><p>The <a href="https://docs.min.io/aistor/developers/sdk/python/api/">SDK documentation</a> also lists bucket and object operations, such as:</p><ul><li>list_buckets,</li><li>bucket_exists,</li><li>make_bucket,</li><li>list_objects,</li><li>copy_object,</li><li>stat_object,</li><li>remove_object,</li><li>remove_objects,</li><li>fput_object, and</li><li>fget_object.</li></ul><h3>Create a configuration file</h3><p>Create config.ini:</p><pre>[minio]<br>endpoint = localhost:9000<br>access_key = devuser<br>secret_key = devpass123<br>secure = false<br>dev_bucket = dev<br>artifact_bucket = ml-artifacts</pre><p>Why use a config file?</p><p>Because later you can change this:</p><ul><li>localhost AIStor</li><li>remote AIStor</li><li>TLS true or false</li><li>access key</li><li>secret key</li><li>bucket names</li></ul><p>without rewriting the application logic.</p><h3>Working with Upload, List, Copy, Move, and Delete Objects Using Python</h3><p>Create aistor_object_demo.py:</p><pre>from configparser import ConfigParser<br>from pathlib import Path<br>from datetime import datetime, timezone<br>import csv<br>import json<br><br>from minio import Minio<br>from minio.commonconfig import CopySource<br>from minio.deleteobjects import DeleteObject<br>from minio.error import S3Error<br><br><br>BASE_DIR = Path(__file__).resolve().parent<br>SAMPLE_DIR = BASE_DIR / &quot;sample_data&quot;<br>DOWNLOAD_DIR = BASE_DIR / &quot;downloads&quot;<br><br><br>def load_config():<br>    config = ConfigParser()<br>    config.read(BASE_DIR / &quot;config.ini&quot;)<br><br>    return {<br>        &quot;endpoint&quot;: config.get(&quot;minio&quot;, &quot;endpoint&quot;),<br>        &quot;access_key&quot;: config.get(&quot;minio&quot;, &quot;access_key&quot;),<br>        &quot;secret_key&quot;: config.get(&quot;minio&quot;, &quot;secret_key&quot;),<br>        &quot;secure&quot;: config.getboolean(&quot;minio&quot;, &quot;secure&quot;),<br>        &quot;dev_bucket&quot;: config.get(&quot;minio&quot;, &quot;dev_bucket&quot;),<br>        &quot;artifact_bucket&quot;: config.get(&quot;minio&quot;, &quot;artifact_bucket&quot;),<br>    }<br><br><br>def get_client():<br>    cfg = load_config()<br><br>    client = Minio(<br>        endpoint=cfg[&quot;endpoint&quot;],<br>        access_key=cfg[&quot;access_key&quot;],<br>        secret_key=cfg[&quot;secret_key&quot;],<br>        secure=cfg[&quot;secure&quot;],<br>    )<br><br>    return client, cfg<br><br><br>def create_sample_files():<br>    SAMPLE_DIR.mkdir(exist_ok=True)<br>    DOWNLOAD_DIR.mkdir(exist_ok=True)<br><br>    transactions_path = SAMPLE_DIR / &quot;transactions.csv&quot;<br>    events_path = SAMPLE_DIR / &quot;events.json&quot;<br>    notes_path = SAMPLE_DIR / &quot;notes.txt&quot;<br>    metrics_path = SAMPLE_DIR / &quot;model_metrics.json&quot;<br><br>    with transactions_path.open(&quot;w&quot;, newline=&quot;&quot;) as f:<br>        writer = csv.DictWriter(<br>            f,<br>            fieldnames=[<br>                &quot;transaction_id&quot;,<br>                &quot;amount&quot;,<br>                &quot;currency&quot;,<br>                &quot;status&quot;,<br>            ],<br>        )<br>        writer.writeheader()<br>        writer.writerow(<br>            {<br>                &quot;transaction_id&quot;: &quot;txn_001&quot;,<br>                &quot;amount&quot;: &quot;1200&quot;,<br>                &quot;currency&quot;: &quot;INR&quot;,<br>                &quot;status&quot;: &quot;approved&quot;,<br>            }<br>        )<br>        writer.writerow(<br>            {<br>                &quot;transaction_id&quot;: &quot;txn_002&quot;,<br>                &quot;amount&quot;: &quot;8500&quot;,<br>                &quot;currency&quot;: &quot;INR&quot;,<br>                &quot;status&quot;: &quot;review&quot;,<br>            }<br>        )<br><br>    events = [<br>        {<br>            &quot;event_id&quot;: &quot;evt_001&quot;,<br>            &quot;source&quot;: &quot;api&quot;,<br>            &quot;event_type&quot;: &quot;object_uploaded&quot;,<br>            &quot;created_at&quot;: datetime.now(timezone.utc).isoformat(),<br>        },<br>        {<br>            &quot;event_id&quot;: &quot;evt_002&quot;,<br>            &quot;source&quot;: &quot;worker&quot;,<br>            &quot;event_type&quot;: &quot;checkpoint_written&quot;,<br>            &quot;created_at&quot;: datetime.now(timezone.utc).isoformat(),<br>        },<br>    ]<br><br>    with events_path.open(&quot;w&quot;) as f:<br>        json.dump(events, f, indent=2)<br><br>    notes_path.write_text(<br>        &quot;AIStor stores objects such as documents, logs, datasets, and model artifacts.\n&quot;<br>    )<br><br>    metrics = {<br>        &quot;model_name&quot;: &quot;fraud-baseline&quot;,<br>        &quot;version&quot;: &quot;v1&quot;,<br>        &quot;accuracy&quot;: 0.91,<br>        &quot;precision&quot;: 0.88,<br>        &quot;recall&quot;: 0.84,<br>        &quot;created_at&quot;: datetime.now(timezone.utc).isoformat(),<br>    }<br><br>    with metrics_path.open(&quot;w&quot;) as f:<br>        json.dump(metrics, f, indent=2)<br><br>    print(&quot;Sample files created.&quot;)<br><br><br>def ensure_bucket(client, bucket_name):<br>    if client.bucket_exists(bucket_name):<br>        print(f&quot;Bucket already exists: {bucket_name}&quot;)<br>        return<br><br>    client.make_bucket(bucket_name)<br>    print(f&quot;Created bucket: {bucket_name}&quot;)<br><br><br>def upload_objects(client, cfg):<br>    dev_bucket = cfg[&quot;dev_bucket&quot;]<br>    artifact_bucket = cfg[&quot;artifact_bucket&quot;]<br><br>    uploads = [<br>        {<br>            &quot;bucket&quot;: dev_bucket,<br>            &quot;object_name&quot;: &quot;raw/transactions/transactions.csv&quot;,<br>            &quot;file_path&quot;: SAMPLE_DIR / &quot;transactions.csv&quot;,<br>            &quot;content_type&quot;: &quot;text/csv&quot;,<br>        },<br>        {<br>            &quot;bucket&quot;: dev_bucket,<br>            &quot;object_name&quot;: &quot;raw/events/events.json&quot;,<br>            &quot;file_path&quot;: SAMPLE_DIR / &quot;events.json&quot;,<br>            &quot;content_type&quot;: &quot;application/json&quot;,<br>        },<br>        {<br>            &quot;bucket&quot;: dev_bucket,<br>            &quot;object_name&quot;: &quot;docs/notes.txt&quot;,<br>            &quot;file_path&quot;: SAMPLE_DIR / &quot;notes.txt&quot;,<br>            &quot;content_type&quot;: &quot;text/plain&quot;,<br>        },<br>        {<br>            &quot;bucket&quot;: artifact_bucket,<br>            &quot;object_name&quot;: &quot;models/fraud-baseline/v1/metrics.json&quot;,<br>            &quot;file_path&quot;: SAMPLE_DIR / &quot;model_metrics.json&quot;,<br>            &quot;content_type&quot;: &quot;application/json&quot;,<br>        },<br>    ]<br><br>    for item in uploads:<br>        result = client.fput_object(<br>            bucket_name=item[&quot;bucket&quot;],<br>            object_name=item[&quot;object_name&quot;],<br>            file_path=str(item[&quot;file_path&quot;]),<br>            content_type=item[&quot;content_type&quot;],<br>            metadata={<br>                &quot;project&quot;: &quot;aistor-medium-demo&quot;,<br>                &quot;owner&quot;: &quot;data-platform&quot;,<br>            },<br>        )<br><br>        print(<br>            &quot;Uploaded:&quot;,<br>            f&quot;bucket={item[&#39;bucket&#39;]}&quot;,<br>            f&quot;object={result.object_name}&quot;,<br>            f&quot;etag={result.etag}&quot;,<br>        )<br><br><br>def list_objects(client, bucket_name, prefix=&quot;&quot;):<br>    print(f&quot;\nObjects in bucket={bucket_name}, prefix=&#39;{prefix}&#39;:&quot;)<br><br>    objects = client.list_objects(<br>        bucket_name=bucket_name,<br>        prefix=prefix,<br>        recursive=True,<br>    )<br><br>    found = False<br>    for obj in objects:<br>        found = True<br>        print(<br>            f&quot;- {obj.object_name} | size={obj.size} | last_modified={obj.last_modified}&quot;<br>        )<br><br>    if not found:<br>        print(&quot;- No objects found.&quot;)<br><br><br>def stat_object(client, bucket_name, object_name):<br>    result = client.stat_object(bucket_name, object_name)<br><br>    print(&quot;\nObject metadata:&quot;)<br>    print(f&quot;Bucket: {bucket_name}&quot;)<br>    print(f&quot;Object: {object_name}&quot;)<br>    print(f&quot;Size: {result.size}&quot;)<br>    print(f&quot;ETag: {result.etag}&quot;)<br>    print(f&quot;Content-Type: {result.content_type}&quot;)<br>    print(f&quot;Last Modified: {result.last_modified}&quot;)<br>    print(f&quot;Metadata: {result.metadata}&quot;)<br><br><br>def download_object(client, bucket_name, object_name, local_file_name):<br>    target_path = DOWNLOAD_DIR / local_file_name<br><br>    client.fget_object(<br>        bucket_name=bucket_name,<br>        object_name=object_name,<br>        file_path=str(target_path),<br>    )<br><br>    print(f&quot;\nDownloaded {object_name} to {target_path}&quot;)<br><br><br>def copy_object(client, bucket_name, source_object, destination_object):<br>    result = client.copy_object(<br>        bucket_name,<br>        destination_object,<br>        CopySource(bucket_name, source_object),<br>    )<br><br>    print(<br>        f&quot;\nCopied object: {source_object} -&gt; {destination_object}, etag={result.etag}&quot;<br>    )<br><br><br>def move_object(client, bucket_name, source_object, destination_object):<br>    copy_object(client, bucket_name, source_object, destination_object)<br><br>    client.remove_object(bucket_name, source_object)<br><br>    print(f&quot;Moved object: {source_object} -&gt; {destination_object}&quot;)<br><br><br>def delete_prefix(client, bucket_name, prefix):<br>    print(f&quot;\nDeleting all objects under prefix: {prefix}&quot;)<br><br>    delete_object_list = map(<br>        lambda obj: DeleteObject(obj.object_name),<br>        client.list_objects(bucket_name, prefix=prefix, recursive=True),<br>    )<br><br>    errors = client.remove_objects(bucket_name, delete_object_list)<br><br>    had_error = False<br>    for error in errors:<br>        had_error = True<br>        print(f&quot;Delete error: {error}&quot;)<br><br>    if not had_error:<br>        print(f&quot;Deleted prefix contents: {prefix}&quot;)<br><br><br>def main():<br>    client, cfg = get_client()<br><br>    dev_bucket = cfg[&quot;dev_bucket&quot;]<br>    artifact_bucket = cfg[&quot;artifact_bucket&quot;]<br><br>    try:<br>        ensure_bucket(client, dev_bucket)<br>        ensure_bucket(client, artifact_bucket)<br><br>        create_sample_files()<br><br>        upload_objects(client, cfg)<br><br>        list_objects(client, dev_bucket)<br>        list_objects(client, artifact_bucket)<br><br>        stat_object(<br>            client,<br>            dev_bucket,<br>            &quot;raw/transactions/transactions.csv&quot;,<br>        )<br><br>        download_object(<br>            client,<br>            dev_bucket,<br>            &quot;raw/transactions/transactions.csv&quot;,<br>            &quot;transactions_downloaded.csv&quot;,<br>        )<br><br>        copy_object(<br>            client,<br>            dev_bucket,<br>            &quot;raw/transactions/transactions.csv&quot;,<br>            &quot;curated/transactions/transactions.csv&quot;,<br>        )<br><br>        move_object(<br>            client,<br>            dev_bucket,<br>            &quot;docs/notes.txt&quot;,<br>            &quot;archive/docs/notes.txt&quot;,<br>        )<br><br>        list_objects(client, dev_bucket)<br><br>        delete_prefix(client, dev_bucket, &quot;archive/&quot;)<br><br>        list_objects(client, dev_bucket)<br><br>    except S3Error as exc:<br>        print(&quot;S3 error occurred:&quot;)<br>        print(f&quot;Code: {exc.code}&quot;)<br>        print(f&quot;Message: {exc.message}&quot;)<br>        print(f&quot;Resource: {exc.resource}&quot;)<br>        raise<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Run it:</p><pre>python aistor_object_demo.py</pre><pre>(.venv) monkey@monkey-Lenovo-G50-80:~/Projects/aistor-demo$ python aistor_object_demo.py<br>Bucket already exists: dev<br>Bucket already exists: ml-artifacts<br>Sample files created.<br>Uploaded: bucket=dev object=raw/transactions/transactions.csv etag=290d074705a14a3e9ec13f48b3ccd47b<br>Uploaded: bucket=dev object=raw/events/events.json etag=2878cc5d732cb729f0d0778fbf7a8221<br>Uploaded: bucket=dev object=docs/notes.txt etag=7de9244afd87eb2a77fe686e4cb56302<br>Uploaded: bucket=ml-artifacts object=models/fraud-baseline/v1/metrics.json etag=447336b89ea0994254cf4fd1f4c44540<br><br>Objects in bucket=dev, prefix=&#39;&#39;:<br>- docs/notes.txt | size=78 | last_modified=2026-05-19 11:43:02.158000+00:00<br>- raw/events/events.json | size=302 | last_modified=2026-05-19 11:43:02.146000+00:00<br>- raw/transactions/transactions.csv | size=91 | last_modified=2026-05-19 11:43:02.133000+00:00<br><br>Objects in bucket=ml-artifacts, prefix=&#39;&#39;:<br>- models/fraud-baseline/v1/metrics.json | size=166 | last_modified=2026-05-19 11:43:02.171000+00:00<br><br>Object metadata:<br>Bucket: dev<br>Object: raw/transactions/transactions.csv<br>Size: 91<br>ETag: 290d074705a14a3e9ec13f48b3ccd47b<br>Content-Type: text/csv<br>Last Modified: 2026-05-19 11:43:02+00:00<br>Metadata: HTTPHeaderDict({&#39;Accept-Ranges&#39;: &#39;bytes&#39;, &#39;Content-Length&#39;: &#39;91&#39;, &#39;Content-Type&#39;: &#39;text/csv&#39;, &#39;ETag&#39;: &#39;&quot;290d074705a14a3e9ec13f48b3ccd47b&quot;&#39;, &#39;Last-Modified&#39;: &#39;Tue, 19 May 2026 11:43:02 GMT&#39;, &#39;Server&#39;: &#39;MinIO AIStor&#39;, &#39;Strict-Transport-Security&#39;: &#39;max-age=31536000; includeSubDomains&#39;, &#39;Vary&#39;: &#39;Origin, Accept-Encoding&#39;, &#39;X-Amz-Id-2&#39;: &#39;dd9025bab4ad464b049177c95eb6ebf374d3b3fd1af9251148b658df7ac2e3e8&#39;, &#39;X-Amz-Request-Id&#39;: &#39;18B0F4C591D96858&#39;, &#39;X-Content-Type-Options&#39;: &#39;nosniff&#39;, &#39;X-Ratelimit-Limit&#39;: &#39;1312&#39;, &#39;X-Ratelimit-Remaining&#39;: &#39;1312&#39;, &#39;X-Xss-Protection&#39;: &#39;1; mode=block&#39;, &#39;x-amz-meta-owner&#39;: &#39;data-platform&#39;, &#39;x-amz-meta-project&#39;: &#39;aistor-medium-demo&#39;, &#39;Date&#39;: &#39;Tue, 19 May 2026 11:43:02 GMT&#39;})<br><br>Downloaded raw/transactions/transactions.csv to /home/monkey/Projects/aistor-demo/downloads/transactions_downloaded.csv<br><br>Copied object: raw/transactions/transactions.csv -&gt; curated/transactions/transactions.csv, etag=290d074705a14a3e9ec13f48b3ccd47b<br><br>Copied object: docs/notes.txt -&gt; archive/docs/notes.txt, etag=7de9244afd87eb2a77fe686e4cb56302<br>Moved object: docs/notes.txt -&gt; archive/docs/notes.txt<br><br>Objects in bucket=dev, prefix=&#39;&#39;:<br>- archive/docs/notes.txt | size=78 | last_modified=2026-05-19 11:43:02.253000+00:00<br>- curated/transactions/transactions.csv | size=91 | last_modified=2026-05-19 11:43:02.235000+00:00<br>- raw/events/events.json | size=302 | last_modified=2026-05-19 11:43:02.146000+00:00<br>- raw/transactions/transactions.csv | size=91 | last_modified=2026-05-19 11:43:02.133000+00:00<br><br>Deleting all objects under prefix: archive/<br>Deleted prefix contents: archive/<br><br>Objects in bucket=dev, prefix=&#39;&#39;:<br>- curated/transactions/transactions.csv | size=91 | last_modified=2026-05-19 11:43:02.235000+00:00<br>- raw/events/events.json | size=302 | last_modified=2026-05-19 11:43:02.146000+00:00<br>- raw/transactions/transactions.csv | size=91 | last_modified=2026-05-19 11:43:02.133000+00:00<br>(.venv) monkey@monkey-Lenovo-G50-80:~/Projects/aistor-demo$ </pre><p>Here we demonstrated:</p><ol><li>connecting to AIStor using the S3-compatible MinIO Python SDK</li><li>creating sample local files</li><li>uploading objects</li><li>using prefixes</li><li>listing objects</li><li>reading object metadata</li><li>downloading objects</li><li>copying objects</li><li>moving objects using copy plus delete</li><li>deleting all objects under a prefix</li><li>storing ML-style artifacts</li></ol><h3>Optional: use boto3 with AIStor</h3><p>Because AIStor is S3-compatible, many applications can also use AWS’s boto3 library by changing the endpoint and credentials.</p><p>Install:</p><pre>pip install boto3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsz2cwqQ-JaMR4dVmLEwaw.png" /><figcaption>Fig: Output #10</figcaption></figure><p>Create boto3_aistor_example.py:</p><pre>import boto3<br>from botocore.client import Config<br><br><br>s3 = boto3.client(<br>    &quot;s3&quot;,<br>    endpoint_url=&quot;http://localhost:9000&quot;,<br>    aws_access_key_id=&quot;devuser&quot;,<br>    aws_secret_access_key=&quot;devpass123&quot;,<br>    config=Config(signature_version=&quot;s3v4&quot;),<br>    region_name=&quot;us-east-1&quot;,<br>)<br><br>bucket = &quot;dev&quot;<br><br>response = s3.list_objects_v2(Bucket=bucket)<br><br>for item in response.get(&quot;Contents&quot;, []):<br>    print(item[&quot;Key&quot;], item[&quot;Size&quot;])</pre><p>Run:</p><pre>python boto3_aistor_example.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*uOuvjh6cFymTSdvGP5cV3w.png" /><figcaption>Fig: Output #11</figcaption></figure><blockquote><strong>This pattern is useful when your code already uses AWS SDKs, Airflow S3 hooks, Spark S3A, MLflow artifact storage, or data lakehouse tools.</strong></blockquote><h3>Versioning, object lock, lifecycle, and observability</h3><p>A serious object store is not only a place to upload files. It is also a governance and operations layer.</p><h4>I. Versioning</h4><p>Versioning keeps older versions of an object when the same object name is overwritten.</p><p>Useful for:</p><ul><li>model rollback</li><li>dataset rollback</li><li>accidental overwrite recovery</li><li>auditability</li><li>reproducible ML runs</li></ul><h4>II. Object lock and immutability</h4><p><a href="https://docs.min.io/aistor/administration/object-locking-and-immutability">AIStor Object Locking</a> enforces WORM, meaning Write-Once Read-Many, to protect versioned objects from deletion. It supports duration-based retention and indefinite legal hold retention.</p><p>Useful for:</p><ul><li>financial records</li><li>security logs</li><li>legal evidence</li><li>compliance retention</li><li>ransomware protection</li><li>audit trails</li></ul><h4>III. Lifecycle management</h4><p>Lifecycle rules automatically expire or transition objects.</p><p>Examples:</p><ul><li>delete tmp/ objects after 7 days</li><li>delete failed pipeline outputs after 30 days</li><li>move older logs to cheaper storage</li><li>retain compliance records for required periods</li></ul><p><a href="https://docs.min.io/aistor/administration/object-lifecycle-management/object-tiering/transition-objects-to-s3/">AIStor lifecycle management</a> supports expiry and transition patterns, including tiering objects to remote S3-compatible storage.</p><h4>IV. Observability</h4><p>AIStor publishes cluster, node, bucket, and resource metrics using the <a href="https://docs.min.io/aistor/operations/monitoring/metrics-and-alerts/collect-minio-metrics-using-prometheus/">Prometheus data model</a>. It also supports audit logging to remote receivers for granular operation tracking.</p><p>For engineers, this matters because object storage can directly affect:</p><ul><li>AI training throughput</li><li>GPU utilization</li><li>pipeline freshness</li><li>API latency</li><li>log retention</li><li>incident response</li><li>data lake query speed</li><li>fraud detection SLAs</li></ul><h3>AIStor use cases</h3><h4>I. AI training</h4><p>AI training needs fast access to datasets, labels, features, checkpoints, and model artifacts.</p><p>A common layout:</p><pre>ml-artifacts/<br>  datasets/<br>    raw/<br>    curated/<br>  features/<br>  checkpoints/<br>  models/<br>  metrics/</pre><p><a href="https://www.min.io/use-cases/ai-training">AIStor’s AI training use case</a> focuses on feeding many training workers in parallel with high throughput and keeping GPUs utilized during large-scale training runs.</p><h4>II. AI inference</h4><p>Inference systems need fast access to models, embeddings, prompts, context, cache data, and generated outputs.</p><p>A common layout:</p><pre>inference-store/<br>  models/<br>  embeddings/<br>  prompts/<br>  context/<br>  outputs/<br>  evaluations/</pre><p><a href="https://www.min.io/use-cases/ai-inference">AIStor’s inference use case</a> includes production inference, KV cache offload, shared context memory, multi-agent coordination, long-context reasoning, and real-time decision workloads.</p><h4>III. Observability and telemetry</h4><p>Modern systems generate logs, metrics, traces, events, and model signals.</p><p>A common layout:</p><pre>observability-lake/<br>  logs/<br>  metrics/<br>  traces/<br>  events/<br>  model-signals/</pre><p><a href="https://www.min.io/use-cases/observability-telemetry">AIStor’s observability use case</a> focuses on storing and querying more telemetry data, extending retention windows, and reducing cost pressure from high-volume logs, metrics, traces, events, and model signals.</p><h4>IV. Financial transactions</h4><p>Financial platforms need reliable storage for transaction data, fraud features, AML investigations, regulatory reporting, and risk analytics.</p><p>A common layout:</p><pre>financial-transactions/<br>  raw/card-payments/<br>  raw/upi/<br>  raw/netbanking/<br>  curated/fraud-features/<br>  risk/daily-calculations/<br>  compliance/aml-reports/</pre><p><a href="https://www.min.io/use-cases/financial-transactions">AIStor’s financial transactions use case</a> focuses on consolidating scattered transaction data into a high-performance platform for fraud detection, AML, compliance, risk analytics, and credit risk pipelines.</p><h4>V. SIEM and security</h4><p>Security teams need long-retention storage for logs, detections, investigation data, and forensic evidence.</p><p>A common layout:</p><pre>security-lake/<br>  raw/firewall/<br>  raw/endpoint/<br>  raw/cloud/<br>  raw/kubernetes/<br>  detections/<br>  forensics/<br>  cases/</pre><p><a href="https://www.min.io/use-cases/siem-security">AIStor’s SIEM use case</a> focuses on active threat detection, threat hunting, incident forensics, UEBA, immutable compliance storage, and historical telemetry search.</p><h4>VI. Industrial and operational technology</h4><p>Factories, energy systems, telecom systems, and industrial environments generate sensor data, machine data, inspection images, and process telemetry.</p><p>A common layout:</p><pre>industrial-data/<br>  raw/sensors/<br>  raw/vision/<br>  raw/scada/<br>  historian/<br>  predictive-maintenance/<br>  quality-inspection/<br>  digital-twin/</pre><p><a href="https://www.min.io/use-cases/industrial-operational-technology">AIStor’s industrial and OT use case</a> includes predictive maintenance, AI-powered quality inspection, raw sensor retention, process data retention, and lakehouse integration for OT analytics.</p><h3>Architecture pattern</h3><p>A modern object-storage-based data platform can look like this:</p><pre>Sources<br>  |<br>  | APIs, apps, logs, sensors, transactions, documents, images<br>  v<br>Ingestion Layer<br>  |<br>  | Airflow, Kafka, Spark, custom workers, agents<br>  v<br>AIStor Object Storage<br>  |<br>  | raw, curated, features, models, logs, audit, checkpoints<br>  v<br>Compute Layer<br>  |<br>  | Spark, Trino, Ray, PyTorch, MLflow, dbt<br>  v<br>Serving Layer<br>  |<br>  | FastAPI, dashboards, BI tools, model APIs, search systems<br>  v<br>Users and Applications</pre><p>The core design principle is:</p><ul><li>Separate storage from compute.</li><li>Store data in S3-compatible object storage.</li><li>Let multiple tools read and write through standard APIs.</li><li>Apply policies, versioning, lifecycle, observability, and audit controls at the storage layer.</li></ul><h3>Production checklist</h3><p>For local learning, the above setup is enough.</p><p>For production, use this checklist:</p><ol><li>Do not use default credentials</li><li>Use TLS</li><li>Use one service user per application</li><li>Apply least-privilege IAM policies</li><li>Enable versioning where rollback matters</li><li>Enable object lock where compliance matters</li><li>Define lifecycle rules for temporary and old data</li><li>Use audit logging for regulated workloads</li><li>Use Prometheus metrics and alerts</li><li>Use distributed architecture for high availability</li><li>Use load balancing for application traffic</li><li>Test disk, node, and network failure scenarios</li><li>Document bucket ownership and retention rules</li><li>Use secret management for credentials</li><li>Benchmark before production rollout</li><li>Review the correct AIStor subscription and license terms</li></ol><h3>Cleanup</h3><p>Stop the container:</p><pre>docker stop aistor-server</pre><p>Remove the container:</p><pre>docker rm aistor-server</pre><p>Remove local generated data:</p><pre>rm -rf $HOME/Projects/aistor-demo/data<br>rm -rf $HOME/Projects/aistor-demo/sample_data<br>rm -rf $HOME/Projects/aistor-demo/downloads<br>rm -rf $HOME/Projects/aistor-demo/.venv</pre><p>Keep your license file only if you need it later:</p><pre>ls $HOME/aistor-demo/minio.license</pre><p>Full cleanup:</p><pre>docker stop aistor-server || true<br>docker rm aistor-server || true<br>rm -rf $HOME/aistor-demo</pre><h3>Conclusion</h3><p>Object storage is one of the most important storage models in modern software engineering. Once you understand objects, buckets, prefixes, metadata, S3 APIs, policies, versioning, lifecycle, and object lock, many data systems become easier to design.</p><p>For junior engineers, the most important lesson is simple: object storage is not just folders in the cloud. It is API-first storage for scalable applications.</p><p>For experienced engineers, the deeper lesson is this: AIStor becomes valuable when treated as a data platform layer, not only a file dumping place. It can support AI training, inference, observability, financial analytics, SIEM, industrial telemetry, lakehouse workloads, and production governance.</p><p>Happy Coding! 🎉🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xo8L17ywFK8YbSmHrbflpA.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10acb6dac40d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Healthcare Revenue & Operations Data Platform]]></title>
            <link>https://medium.com/@thisis-Shitanshu/building-a-healthcare-revenue-operations-data-platform-83d104ec9303?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d104ec9303</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[healthcare-analytics]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 09:09:45 GMT</pubDate>
            <atom:updated>2026-04-02T09:27:12.181Z</atom:updated>
            <content:encoded><![CDATA[<h4>A local-first, end-to-end healthcare revenue cycle analytics platform built with Spark, Iceberg, Airflow, AWS, and Snowflake for billing, finance, operations, and compliance analytics.</h4><p>Assume you are supporting a U.S. healthcare provider organization with multiple facilities and provider groups. Revenue data is arriving from billing vendors, clearinghouses, payer remittance systems, operational work queues, and patient-access systems. The business wants one platform that answers questions like:</p><ul><li>Which facilities have high denial rates?</li><li>Where are reimbursements getting delayed?</li><li>Which workflow stage causes rework?</li><li>Are patient access improvements actually improving conversions?</li></ul><p>The engineering challenge is not only to load files. It is to build a system that is <strong>auditable, idempotent, cost-aware, scalable, and secure</strong>, while producing data products that finance, operations, compliance, and analytics teams can trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*zt7XH3aH0R55--3DurygAg.png" /><figcaption>Fig: <a href="https://en.wikipedia.org/wiki/United_States_Department_of_Health_and_Human_Services">United States Department of Health and Human Services</a></figcaption></figure><h3>Note</h3><p>For U.S. healthcare workload, your design has to begin with <strong>HIPAA and HITECH</strong>, not with Spark code. HIPAA Privacy Rule governs protected health information and who may use or disclose it. HIPAA Security Rule governs administrative, physical, and technical safeguards for electronic PHI. HITECH strengthened breach notification and enforcement expectations. HHS also provides formal de-identification guidance under the Privacy Rule. In practice, you must distinguish <strong>legal/regulatory requirements</strong> from <strong>security best practices</strong> and from <strong>enterprise expectations</strong>. For example, minimum-necessary access, BAAs, breach handling, and documented safeguards are legal issues. KMS-backed encryption, no-public-IP architectures, CI/CD signing, and data contracts are engineering best practices. HITRUST alignment, centralized policy-as-code, and column-level governance in the warehouse are often enterprise expectations layered on top. AWS states that PHI workloads require a BAA and use of HIPAA-eligible services. Snowflake’s terms likewise say customers should not process HIPAA data in the service unless a BAA is in place.</p><blockquote>We will use <strong>public or synthetic data only</strong>, so you can safely build and test the platform without handling live PHI.</blockquote><blockquote>This project is HIPAA/HITECH-aware but not fully HIPAA/HITECH compliant yet; it already has useful technical safeguards like encrypted and private S3 buckets, Snowflake role-based access, restricted Snowflake stage access to S3, data contracts and quality checks, idempotent ingest tracking, and SNS failure alerts, and it also uses public/synthetic data to reduce PHI risk, but key compliance pieces are still missing for production, such as formal BAA/legal controls, stronger secrets management and rotation (instead of plain `.env`), full audit/governance controls, KMS key strategy, private-network architecture, and documented risk/breach response processes.</blockquote><p>For deeper reading, start here:</p><ul><li>HHS HIPAA Privacy Rule summary (<a href="https://www.hhs.gov/hipaa/for-professionals/privacy/laws-regulations/index.html">HHS.gov</a>)</li><li>HHS HIPAA Security Rule summary (<a href="https://www.hhs.gov/hipaa/for-professionals/security/laws-regulations/index.html?utm_source=chatgpt.com">HHS.gov</a>)</li><li>HHS de-identification guidance (<a href="https://www.hhs.gov/hipaa/for-professionals/special-topics/de-identification/index.html?utm_source=chatgpt.com">HHS.gov</a>)</li><li>HHS minimum necessary guidance (<a href="https://www.hhs.gov/hipaa/for-professionals/privacy/guidance/minimum-necessary-requirement/index.html">HHS.gov</a>)</li><li>HHS business associate guidance and sample BAA provisions (<a href="https://www.hhs.gov/hipaa/for-professionals/privacy/guidance/business-associates/index.html">HHS.gov</a>)</li><li>HHS breach notification guidance (<a href="https://www.hhs.gov/hipaa/for-professionals/breach-notification/index.html">HHS.gov</a>)</li><li>AWS HIPAA compliance page (<a href="https://aws.amazon.com/compliance/hipaa-compliance/">Amazon Web Services, Inc.</a>)</li></ul><p>A few precise compliance points matter immediately:</p><ul><li>HIPAA does not generally set medical record retention periods. State law usually governs that. But HIPAA does require retention of certain required documentation for six years, and required safeguards apply for as long as PHI is maintained. (<a href="https://www.hhs.gov/hipaa/for-professionals/security/laws-regulations/index.html">HHS.gov</a>)</li><li>De-identification under HIPAA is not “we removed a name.” HHS recognizes specific methods, including Expert Determination and Safe Harbor. (<a href="https://www.hhs.gov/hipaa/for-professionals/special-topics/de-identification/index.html?utm_source=chatgpt.com">HHS.gov</a>)</li><li>Minimum-necessary access is a core privacy principle and should appear in IAM, row access, data masking, and workload design. (<a href="https://www.hhs.gov/hipaa/for-professionals/privacy/guidance/minimum-necessary-requirement/index.html">HHS.gov</a>)</li></ul><h3><strong>What we will build</strong></h3><p>We will build a full local-first pipeline that runs on your machine but writes to AWS and loads Snowflake.</p><h4><strong>#1 End-to-end flow</strong></h4><ol><li>Download public healthcare-like source data.</li><li>Build realistic seed datasets.</li><li>Simulate vendor feeds.</li><li>Land feeds into S3 Bronze (idempotent ingestion).</li><li>Transform Bronze to Iceberg Silver.</li><li>Build Gold KPIs and export to S3 for Snowflake.</li><li>Run quality checks.</li><li>Load Gold exports into Snowflake (mandatory final DAG step).</li></ol><h4>#2 Architecture</h4><p>The current implementation is local-first (no EC2 SSH path, no EMR/ECS runtime path for data jobs).</p><ul><li><strong>Orchestration:</strong> airflow/dags/rcm_platform_dag.py</li><li><strong>Spark runtime:</strong> docker compose --profile spark run --rm spark spark-submit ...</li><li><strong>Lakehouse storage:</strong> S3 + Iceberg tables in Glue Catalog</li><li><strong>Serving:</strong> Snowflake curated tables and executive view</li><li><strong>Alerting:</strong> SNS callback on Airflow task failure</li></ul><h4><strong>#3 DAG order</strong></h4><p>download_public_raw -&gt; seed_public_data -&gt; build_vendor_feeds -&gt; ingest_vendor_feeds_to_bronze -&gt; bronze_to_silver -&gt; silver_to_gold -&gt; quality_checks -&gt; load_gold_to_snowflake</p><h4>#4 Repo structure</h4><pre>.<br>├── .env.example<br>├── .github<br>│   └── workflows<br>│       ├── app.yml<br>│       └── infra.yml<br>├── .gitignore<br>├── Makefile<br>├── README.md<br>├── airflow<br>│   ├── dags<br>│   │   └── rcm_platform_dag.py<br>│   ├── plugins<br>│   │   └── callbacks.py<br>│   └── requirements.txt<br>├── apps<br>│   ├── ingestion<br>│   │   ├── input_script.py<br>│   │   └── local_bronze_ingest.py<br>│   ├── simulation<br>│   │   ├── build_vendor_feeds.py<br>│   │   └── seed_public_data.py<br>│   └── snowflake<br>│       └── load_gold_exports.py<br>├── aws-instance-types.txt<br>├── config<br>│   ├── data_contracts.yaml<br>│   └── datasets.yaml<br>├── docker<br>│   └── spark.Dockerfile<br>├── docker-compose.yml<br>├── infra<br>│   └── terraform<br>│       ├── main.tf<br>│       ├── outputs.tf<br>│       ├── providers.tf<br>│       ├── terraform.tfvars<br>│       ├── terraform.tfvars.example<br>│       ├── tf_with_aws_login.sh<br>│       └── variables.tf<br>├── output.txt<br>├── requirements.txt<br>├── snowflake<br>│   ├── 01_security_and_warehouse.sql<br>│   ├── 02_stages_and_tables.sql<br>│   └── 03_copy_and_views.sql<br>├── spark<br>│   ├── bronze_to_silver.py<br>│   ├── iceberg_maintenance.py<br>│   ├── quality_checks.py<br>│   └── silver_to_gold.py<br>└── tests<br>    ├── conftest.py<br>    ├── test_build_vendor_feeds.py<br>    └── test_quality_logic.py</pre><h4>#5 Key project files</h4><ul><li>DAG: airflow/dags/rcm_platform_dag.py</li></ul><pre>import os<br>import shlex<br>from datetime import datetime<br>from pathlib import Path<br><br>from airflow import DAG<br>from airflow.operators.bash import BashOperator<br><br>from callbacks import notify_sns<br><br><br>def require_env(name: str) -&gt; str:<br>    value = os.getenv(name)<br>    if not value:<br>        raise ValueError(f&quot;Missing required environment variable: {name}&quot;)<br>    return value<br><br><br>def ensure_required_spark_packages(raw_packages: str) -&gt; str:<br>    required = [<br>        &quot;org.apache.hadoop:hadoop-aws:3.3.4&quot;,<br>    ]<br>    parts = [p.strip() for p in raw_packages.split(&quot;,&quot;) if p.strip()]<br>    seen_ga = {&quot;:&quot;.join(p.split(&quot;:&quot;)[:2]) for p in parts if &quot;:&quot; in p}<br>    for pkg in required:<br>        ga = &quot;:&quot;.join(pkg.split(&quot;:&quot;)[:2])<br>        if ga not in seen_ga:<br>            parts.append(pkg)<br>            seen_ga.add(ga)<br>    return &quot;,&quot;.join(parts)<br><br><br>AWS_PROFILE = os.getenv(&quot;AWS_PROFILE&quot;, &quot;default&quot;).strip()<br>SPARK_PACKAGES = ensure_required_spark_packages(<br>    os.getenv(<br>        &quot;SPARK_PACKAGES&quot;,<br>        &quot;org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.6.1,org.apache.iceberg:iceberg-aws-bundle:1.6.1,org.apache.hadoop:hadoop-aws:3.3.4&quot;,<br>    ).strip()<br>)<br>SPARK_LOCAL_MASTER = os.getenv(&quot;SPARK_LOCAL_MASTER&quot;, &quot;local[2]&quot;).strip()<br>SPARK_LOCAL_WRITE_MODE = os.getenv(&quot;SPARK_LOCAL_WRITE_MODE&quot;, &quot;replace&quot;).strip().lower()<br>SPARK_DRIVER_MEMORY = os.getenv(&quot;SPARK_DRIVER_MEMORY&quot;, &quot;2g&quot;).strip()<br>SPARK_EXECUTOR_MEMORY = os.getenv(&quot;SPARK_EXECUTOR_MEMORY&quot;, &quot;4g&quot;).strip()<br>SPARK_SHUFFLE_PARTITIONS = os.getenv(&quot;SPARK_SHUFFLE_PARTITIONS&quot;, &quot;64&quot;).strip()<br>RAW_DOWNLOAD_CHUNK_MB = os.getenv(&quot;RAW_DOWNLOAD_CHUNK_MB&quot;, &quot;8&quot;).strip()<br>SNOWFLAKE_LOAD_SQL = os.getenv(&quot;SNOWFLAKE_LOAD_SQL&quot;, &quot;snowflake/03_copy_and_views.sql&quot;).strip()<br><br>DATA_BUCKET = require_env(&quot;DATA_BUCKET&quot;)<br>ICEBERG_WAREHOUSE = require_env(&quot;ICEBERG_WAREHOUSE&quot;)<br><br>if SPARK_LOCAL_WRITE_MODE not in {&quot;merge&quot;, &quot;replace&quot;}:<br>    raise ValueError(&quot;SPARK_LOCAL_WRITE_MODE must be one of: merge, replace&quot;)<br><br>DAG_DIR = Path(__file__).resolve().parent<br>REPO_ROOT = DAG_DIR.parent.parent<br><br>venv_prefix = &quot;. .venv/bin/activate &amp;&amp; &quot;<br>cred_bootstrap = (<br>    f&#39;eval &quot;$(aws configure export-credentials --profile {shlex.quote(AWS_PROFILE)} --format env)&quot; &amp;&amp; &#39;<br>)<br>spark_submit_prefix = (<br>    cred_bootstrap<br>    + &quot;docker compose --profile spark run --rm spark &quot;<br>    + &quot;spark-submit &quot;<br>    + f&quot;--master {shlex.quote(SPARK_LOCAL_MASTER)} &quot;<br>    + &quot;--conf spark.hadoop.fs.s3a.impl=org.apache.hadoop.fs.s3a.S3AFileSystem &quot;<br>    + &quot;--conf spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem &quot;<br>    + &quot;--conf spark.hadoop.fs.s3n.impl=org.apache.hadoop.fs.s3a.S3AFileSystem &quot;<br>    + &quot;--conf spark.sql.iceberg.vectorization.enabled=false &quot;<br>    + &quot;--conf spark.sql.parquet.enableVectorizedReader=false &quot;<br>    + &quot;--conf spark.sql.parquet.enableNestedColumnVectorizedReader=false &quot;<br>    + f&quot;--conf spark.driver.memory={shlex.quote(SPARK_DRIVER_MEMORY)} &quot;<br>    + f&quot;--conf spark.executor.memory={shlex.quote(SPARK_EXECUTOR_MEMORY)} &quot;<br>    + &quot;--conf spark.executor.cores=1 &quot;<br>    + f&quot;--conf spark.sql.shuffle.partitions={shlex.quote(SPARK_SHUFFLE_PARTITIONS)} &quot;<br>    + &quot;--conf spark.sql.adaptive.enabled=true &quot;<br>    + &quot;--conf spark.sql.files.maxPartitionBytes=67108864 &quot;<br>    + f&quot;--packages {shlex.quote(SPARK_PACKAGES)} &quot;<br>)<br><br>default_args = {<br>    &quot;owner&quot;: &quot;data-platform&quot;,<br>    &quot;depends_on_past&quot;: False,<br>    &quot;retries&quot;: 1,<br>    &quot;on_failure_callback&quot;: notify_sns,<br>}<br><br>with DAG(<br>    dag_id=&quot;hc_rcm_platform_daily&quot;,<br>    start_date=datetime(2026, 3, 1),<br>    schedule=&quot;0 6 * * *&quot;,<br>    catchup=False,<br>    default_args=default_args,<br>    template_searchpath=[str(REPO_ROOT), &quot;/usr/local/airflow&quot;],<br>    tags=[&quot;healthcare&quot;, &quot;rcm&quot;, &quot;local&quot;, &quot;iceberg&quot;],<br>) as dag:<br><br>    download_public_raw = BashOperator(<br>        task_id=&quot;download_public_raw&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{venv_prefix}python apps/ingestion/input_script.py &quot;<br>            f&quot;--chunk-size-mb {shlex.quote(RAW_DOWNLOAD_CHUNK_MB)}&quot;<br>        ),<br>    )<br><br>    seed_public_data = BashOperator(<br>        task_id=&quot;seed_public_data&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{venv_prefix}python apps/simulation/seed_public_data.py &quot;<br>            &quot;--config config/datasets.yaml&quot;<br>        ),<br>    )<br><br>    build_vendor_feeds = BashOperator(<br>        task_id=&quot;build_vendor_feeds&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{venv_prefix}python apps/simulation/build_vendor_feeds.py &quot;<br>            &quot;--seed-dir ./data/public_seed &quot;<br>            &quot;--output-dir ./data/vendor_feeds &quot;<br>            + &quot;--run-date {{ ds }}&quot;<br>        ),<br>    )<br><br>    ingest_vendor_feeds_to_bronze = BashOperator(<br>        task_id=&quot;ingest_vendor_feeds_to_bronze&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{venv_prefix}{cred_bootstrap}python apps/ingestion/local_bronze_ingest.py &quot;<br>            f&quot;--data-bucket {shlex.quote(DATA_BUCKET)} &quot;<br>            &quot;--feeds-dir ./data/vendor_feeds &quot;<br>            + &quot;--run-date {{ ds }}&quot;<br>        ),<br>    )<br><br>    bronze_to_silver = BashOperator(<br>        task_id=&quot;bronze_to_silver&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{spark_submit_prefix}spark/bronze_to_silver.py &quot;<br>            f&quot;--warehouse {shlex.quote(ICEBERG_WAREHOUSE)} &quot;<br>            f&quot;--data-bucket {shlex.quote(DATA_BUCKET)} &quot;<br>            &quot;--contracts config/data_contracts.yaml &quot;<br>            f&quot;--write-mode {shlex.quote(SPARK_LOCAL_WRITE_MODE)}&quot;<br>        ),<br>    )<br><br>    silver_to_gold = BashOperator(<br>        task_id=&quot;silver_to_gold&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{spark_submit_prefix}spark/silver_to_gold.py &quot;<br>            f&quot;--warehouse {shlex.quote(ICEBERG_WAREHOUSE)} &quot;<br>            f&quot;--data-bucket {shlex.quote(DATA_BUCKET)} &quot;<br>            + &quot;--run-date {{ ds }} &quot;<br>            + f&quot;--write-mode {shlex.quote(SPARK_LOCAL_WRITE_MODE)}&quot;<br>        ),<br>    )<br><br>    quality_checks = BashOperator(<br>        task_id=&quot;quality_checks&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{spark_submit_prefix}spark/quality_checks.py &quot;<br>            f&quot;--warehouse {shlex.quote(ICEBERG_WAREHOUSE)} &quot;<br>            &quot;--contracts config/data_contracts.yaml&quot;<br>        ),<br>    )<br><br>    load_gold_to_snowflake = BashOperator(<br>        task_id=&quot;load_gold_to_snowflake&quot;,<br>        cwd=str(REPO_ROOT),<br>        bash_command=(<br>            f&quot;{venv_prefix}python apps/snowflake/load_gold_exports.py &quot;<br>            + &quot;--run-date {{ ds }} &quot;<br>            + f&quot;--sql-file {shlex.quote(SNOWFLAKE_LOAD_SQL)}&quot;<br>        ),<br>    )<br><br>    (<br>        download_public_raw<br>        &gt;&gt; seed_public_data<br>        &gt;&gt; build_vendor_feeds<br>        &gt;&gt; ingest_vendor_feeds_to_bronze<br>        &gt;&gt; bronze_to_silver<br>        &gt;&gt; silver_to_gold<br>        &gt;&gt; quality_checks<br>        &gt;&gt; load_gold_to_snowflake<br>    )</pre><ul><li>Raw download: apps/ingestion/input_script.py</li></ul><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>Download CMS DE-SynPUF ZIP files into temp storage and extract CSV files into data/public_raw.<br><br>Key behavior:<br>- Streams downloads in chunks (no full file in memory).<br>- Supports resume with .part files when server supports HTTP Range.<br>- Shows progress bars for download and extraction.<br>- Extracts only CSV files.<br>- Auto-downloads external `nppes.csv` and `hospital_general_information.csv` when missing.<br>- Verifies which project raw inputs are present after extraction.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br>import argparse<br>import re<br>import shutil<br>import sys<br>import time<br>import zipfile<br>from html.parser import HTMLParser<br>from pathlib import Path<br>from urllib.parse import unquote, urljoin, urlparse<br><br>import requests<br>from requests.adapters import HTTPAdapter<br>from urllib3.util.retry import Retry<br><br>CMS_PAGE_URL = (<br>    &quot;https://www.cms.gov/data-research/statistics-trends-and-reports/&quot;<br>    &quot;medicare-claims-synthetic-public-use-files&quot;<br>)<br>NPPES_FILES_PAGE_URL = &quot;https://download.cms.gov/nppes/NPI_Files.html&quot;<br>HOSPITAL_GENERAL_INFO_URL = (<br>    &quot;https://data.cms.gov/provider-data/sites/default/files/resources/&quot;<br>    &quot;893c372430d9d71a1c52737d01239d47_1770163599/Hospital_General_Information.csv&quot;<br>)<br><br>PROJECT_REQUIRED_PATTERNS = {<br>    &quot;beneficiary_csv&quot;: &quot;*Beneficiary*csv&quot;,<br>    &quot;inpatient_claims_csv&quot;: &quot;*Inpatient*Claims*csv&quot;,<br>    &quot;outpatient_claims_csv&quot;: &quot;*Outpatient*Claims*csv&quot;,<br>    &quot;carrier_claims_csv&quot;: &quot;*Carrier*Claims*csv&quot;,<br>    &quot;nppes_csv&quot;: &quot;nppes.csv&quot;,<br>    &quot;hospital_general_information_csv&quot;: &quot;hospital_general_information.csv&quot;,<br>}<br><br>CMS_REQUIRED_CATEGORIES = {<br>    &quot;beneficiary&quot;: re.compile(r&quot;beneficiary&quot;, re.IGNORECASE),<br>    &quot;inpatient_claims&quot;: re.compile(r&quot;inpatient.*claims|claims.*inpatient&quot;, re.IGNORECASE),<br>    &quot;outpatient_claims&quot;: re.compile(r&quot;outpatient.*claims|claims.*outpatient&quot;, re.IGNORECASE),<br>    &quot;carrier_claims&quot;: re.compile(r&quot;carrier.*claims|claims.*carrier&quot;, re.IGNORECASE),<br>}<br><br>SAMPLE_PAGE_HINT = re.compile(r&quot;de10-sample-\d+&quot;, re.IGNORECASE)<br>SAMPLE_ONE_PAGE_HINT = re.compile(r&quot;de10-sample-1(?:$|[/?#])&quot;, re.IGNORECASE)<br>SAMPLE_ONE_FILE_HINT = re.compile(r&quot;_sample_1(?:[ab])?(?:[_.]|$)&quot;, re.IGNORECASE)<br>PROJECT_DATA_FILENAME_HINT = re.compile(<br>    r&quot;(beneficiary_summary_file|inpatient_claims|outpatient_claims|carrier_claims)&quot;,<br>    re.IGNORECASE,<br>)<br>FALLBACK_SAMPLE_ONE_PATH = (<br>    &quot;cms-2008-2010-data-entrepreneurs-synthetic-public-use-file-de-synpuf/de10-sample-1&quot;<br>)<br>NPPES_EXCLUDE_HINTS = (&quot;weekly&quot;, &quot;deactivation&quot;, &quot;reactivation&quot;)<br><br><br>def format_bytes(num: float) -&gt; str:<br>    units = [&quot;B&quot;, &quot;KB&quot;, &quot;MB&quot;, &quot;GB&quot;, &quot;TB&quot;]<br>    value = float(num)<br>    for unit in units:<br>        if value &lt; 1024.0 or unit == units[-1]:<br>            return f&quot;{value:.2f}{unit}&quot;<br>        value /= 1024.0<br>    return f&quot;{value:.2f}TB&quot;<br><br><br>class ProgressBar:<br>    def __init__(self, label: str, total: int) -&gt; None:<br>        self.label = label[:24]<br>        self.total = max(total, 0)<br>        self.current = 0<br>        self.started_at = time.time()<br>        self.last_render_at = 0.0<br>        self.last_message_len = 0<br>        self.enabled = sys.stdout.isatty()<br><br>    def set(self, value: int, force: bool = False) -&gt; None:<br>        self.current = max(value, 0)<br>        self._render(force=force)<br><br>    def _render(self, force: bool = False) -&gt; None:<br>        if not self.enabled:<br>            return<br>        now = time.time()<br>        if not force and (now - self.last_render_at) &lt; 0.1:<br>            return<br>        self.last_render_at = now<br>        elapsed = max(now - self.started_at, 1e-6)<br>        speed = self.current / elapsed<br><br>        if self.total &gt; 0:<br>            ratio = min(self.current / self.total, 1.0)<br>            width = 28<br>            done = int(width * ratio)<br>            bar = &quot;#&quot; * done + &quot;-&quot; * (width - done)<br>            body = (<br>                f&quot;\r{self.label:24} [{bar}] {ratio * 100:6.2f}% &quot;<br>                f&quot;{format_bytes(self.current)}/{format_bytes(self.total)} &quot;<br>                f&quot;{format_bytes(speed)}/s&quot;<br>            )<br>        else:<br>            body = (<br>                f&quot;\r{self.label:24} {format_bytes(self.current)} &quot;<br>                f&quot;{format_bytes(speed)}/s&quot;<br>            )<br>        pad = &quot;&quot;<br>        body_len = len(body)<br>        if body_len &lt; self.last_message_len:<br>            pad = &quot; &quot; * (self.last_message_len - body_len)<br>        message = f&quot;{body}{pad}&quot;<br>        sys.stdout.write(message)<br>        sys.stdout.flush()<br>        self.last_message_len = len(message)<br><br>    def close(self) -&gt; None:<br>        if not self.enabled:<br>            return<br>        self._render(force=True)<br>        sys.stdout.write(&quot;\n&quot;)<br>        sys.stdout.flush()<br><br><br>class LinkParser(HTMLParser):<br>    def __init__(self) -&gt; None:<br>        super().__init__()<br>        self.links: list[str] = []<br><br>    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -&gt; None:<br>        if tag.lower() != &quot;a&quot;:<br>            return<br>        attr_map = dict(attrs)<br>        href = attr_map.get(&quot;href&quot;)<br>        if href:<br>            self.links.append(href)<br><br><br>def build_session() -&gt; requests.Session:<br>    retry = Retry(<br>        total=5,<br>        connect=5,<br>        read=5,<br>        backoff_factor=1.5,<br>        status_forcelist=(429, 500, 502, 503, 504),<br>        allowed_methods=(&quot;GET&quot;, &quot;HEAD&quot;),<br>    )<br>    adapter = HTTPAdapter(max_retries=retry)<br>    session = requests.Session()<br>    session.mount(&quot;https://&quot;, adapter)<br>    session.mount(&quot;http://&quot;, adapter)<br>    return session<br><br><br>def ensure_free_space(directory: Path, required_bytes: int, overhead_ratio: float = 1.10) -&gt; None:<br>    if required_bytes &lt;= 0:<br>        return<br>    usage = shutil.disk_usage(directory)<br>    needed = int(required_bytes * overhead_ratio)<br>    if usage.free &lt; needed:<br>        raise RuntimeError(<br>            f&quot;Not enough disk space in {directory}. &quot;<br>            f&quot;Need ~{format_bytes(needed)}, free={format_bytes(usage.free)}.&quot;<br>        )<br><br><br>def unique(items: list[str]) -&gt; list[str]:<br>    seen: set[str] = set()<br>    out: list[str] = []<br>    for item in items:<br>        key = item.strip()<br>        if key and key not in seen:<br>            seen.add(key)<br>            out.append(key)<br>    return out<br><br><br>def looks_like_zip(url: str) -&gt; bool:<br>    lowered = url.lower()<br>    return &quot;.zip&quot; in lowered or &quot;format=zip&quot; in lowered<br><br><br>def extract_links(base_url: str, html: str) -&gt; list[str]:<br>    parser = LinkParser()<br>    parser.feed(html)<br>    resolved_urls: list[str] = []<br>    for href in parser.links:<br>        abs_url = urljoin(base_url, href)<br>        parsed = urlparse(abs_url)<br>        if parsed.scheme not in {&quot;http&quot;, &quot;https&quot;}:<br>            continue<br>        resolved_urls.append(abs_url.split(&quot;#&quot;, 1)[0])<br>    return unique(resolved_urls)<br><br><br>def category_from_filename(name: str) -&gt; str | None:<br>    lowered = name.lower()<br>    if &quot;beneficiary&quot; in lowered:<br>        return &quot;beneficiary&quot;<br>    if &quot;inpatient&quot; in lowered and &quot;claims&quot; in lowered:<br>        return &quot;inpatient_claims&quot;<br>    if &quot;outpatient&quot; in lowered and &quot;claims&quot; in lowered:<br>        return &quot;outpatient_claims&quot;<br>    if &quot;carrier&quot; in lowered and &quot;claims&quot; in lowered:<br>        return &quot;carrier_claims&quot;<br>    return None<br><br><br>def is_project_data_zip(url: str) -&gt; bool:<br>    name = filename_from_https://medium.com/url(url)<br>    lowered = name.lower()<br>    if &quot;.zip&quot; not in lowered:<br>        return False<br>    if &quot;_sample_&quot; not in lowered:<br>        return False<br>    return bool(PROJECT_DATA_FILENAME_HINT.search(lowered))<br><br><br>def is_sample_one_zip(url: str) -&gt; bool:<br>    return bool(SAMPLE_ONE_FILE_HINT.search(filename_from_https://medium.com/url(url).lower()))<br><br><br>def fallback_sample_pages(cms_page_url: str) -&gt; list[str]:<br>    base = cms_page_url.rstrip(&quot;/&quot;)<br>    return [f&quot;{base}/{FALLBACK_SAMPLE_ONE_PATH}&quot;]<br><br><br>def discover_zip_urls(session: requests.Session, cms_page_url: str) -&gt; list[str]:<br>    response = session.get(cms_page_url, timeout=(15, 90))<br>    response.raise_for_status()<br><br>    root_links = extract_links(cms_page_url, response.text)<br>    direct_zip_links = [<br>        url<br>        for url in root_links<br>        if looks_like_zip(url) and is_project_data_zip(url) and is_sample_one_zip(url)<br>    ]<br>    if direct_zip_links:<br>        return unique(direct_zip_links)<br><br>    sample_pages = [<br>        url for url in root_links<br>        if SAMPLE_ONE_PAGE_HINT.search(url)<br>    ]<br>    if not sample_pages:<br>        sample_pages = [url for url in root_links if SAMPLE_PAGE_HINT.search(url)]<br>    if not sample_pages:<br>        sample_pages = fallback_sample_pages(cms_page_url)<br><br>    all_zip_links: list[str] = []<br>    for page_url in sample_pages:<br>        try:<br>            page_response = session.get(page_url, timeout=(15, 90))<br>            page_response.raise_for_status()<br>        except requests.RequestException:<br>            continue<br>        page_links = extract_links(page_url, page_response.text)<br>        all_zip_links.extend(<br>            [<br>                url for url in page_links<br>                if looks_like_zip(url) and is_project_data_zip(url) and is_sample_one_zip(url)<br>            ]<br>        )<br><br>    return unique(all_zip_links)<br><br><br>def filename_from_url(/service/url: str) -&gt; str:<br>    parsed = urlparse(url)<br>    name = Path(unquote(parsed.path)).name<br>    if not name:<br>        name = &quot;download.zip&quot;<br>    if &quot;.zip&quot; not in name.lower():<br>        name = f&quot;{name}.zip&quot;<br>    return name<br><br><br>def select_required_cms_urls(zip_urls: list[str]) -&gt; list[str]:<br>    project_zips = [<br>        url for url in zip_urls<br>        if is_project_data_zip(url) and is_sample_one_zip(url)<br>    ]<br>    if not project_zips:<br>        raise RuntimeError(<br>            &quot;No required sample-1 DE-SynPUF ZIP links were found in discovered CMS links. &quot;<br>            &quot;Pass explicit links using --url as fallback.&quot;<br>        )<br><br>    candidate_pool = project_zips<br><br>    categorized: dict[str, list[str]] = {key: [] for key in CMS_REQUIRED_CATEGORIES}<br>    for url in candidate_pool:<br>        category = category_from_filename(filename_from_https://medium.com/url(url))<br>        if category:<br>            categorized[category].append(url)<br><br>    missing = [key for key, urls in categorized.items() if not urls]<br>    if missing:<br>        missing_list = &quot;, &quot;.join(missing)<br>        raise RuntimeError(<br>            &quot;Could not find required DE-SynPUF ZIP links for: &quot;<br>            f&quot;{missing_list}. Pass explicit links using --url as fallback.&quot;<br>        )<br><br>    selected: list[str] = []<br>    for urls in categorized.values():<br>        selected.extend(urls)<br>    return unique(sorted(selected, key=lambda url: filename_from_https://medium.com/url(url).lower()))<br><br><br>def remote_total_size(response: requests.Response, resume_from: int) -&gt; int:<br>    content_range = response.headers.get(&quot;Content-Range&quot;, &quot;&quot;)<br>    if &quot;/&quot; in content_range:<br>        tail = content_range.rsplit(&quot;/&quot;, 1)[-1]<br>        if tail.isdigit():<br>            return int(tail)<br><br>    content_length = response.headers.get(&quot;Content-Length&quot;)<br>    if content_length and content_length.isdigit():<br>        size = int(content_length)<br>        if response.status_code == 206:<br>            return resume_from + size<br>        return size<br>    return 0<br><br><br>def download_file(<br>    session: requests.Session,<br>    url: str,<br>    temp_dir: Path,<br>    chunk_size: int,<br>    overwrite: bool,<br>) -&gt; Path:<br>    filename = filename_from_https://medium.com/url(url)<br>    target = temp_dir / filename<br>    part = target.with_suffix(target.suffix + &quot;.part&quot;)<br><br>    if target.exists() and not overwrite:<br>        print(f&quot;[skip] Already downloaded: {target.name}&quot;)<br>        return target<br><br>    resume_from = part.stat().st_size if part.exists() else 0<br>    headers: dict[str, str] = {}<br>    if resume_from &gt; 0:<br>        headers[&quot;Range&quot;] = f&quot;bytes={resume_from}-&quot;<br><br>    with session.get(url, stream=True, timeout=(15, 300), headers=headers) as response:<br>        if response.status_code == 416 and part.exists():<br>            part.replace(target)<br>            print(f&quot;[resume] Completed from partial file: {target.name}&quot;)<br>            return target<br><br>        response.raise_for_status()<br><br>        if resume_from &gt; 0 and response.status_code != 206:<br>            part.unlink(missing_ok=True)<br>            resume_from = 0<br><br>        total_bytes = remote_total_size(response, resume_from)<br>        if total_bytes &gt; resume_from:<br>            ensure_free_space(temp_dir, total_bytes - resume_from)<br><br>        write_mode = &quot;ab&quot; if resume_from &gt; 0 and response.status_code == 206 else &quot;wb&quot;<br>        if write_mode == &quot;wb&quot;:<br>            part.unlink(missing_ok=True)<br>            bytes_written = 0<br>        else:<br>            bytes_written = resume_from<br><br>        progress = ProgressBar(label=f&quot;download:{target.name}&quot;, total=total_bytes)<br>        progress.set(bytes_written, force=True)<br><br>        with part.open(write_mode) as handle:<br>            for chunk in response.iter_content(chunk_size=chunk_size):<br>                if not chunk:<br>                    continue<br>                handle.write(chunk)<br>                bytes_written += len(chunk)<br>                progress.set(bytes_written)<br><br>        progress.close()<br><br>    part.replace(target)<br>    return target<br><br><br>def extract_zip(<br>    zip_path: Path,<br>    output_dir: Path,<br>    chunk_size: int,<br>    overwrite: bool,<br>) -&gt; list[Path]:<br>    extracted_paths: list[Path] = []<br>    with zipfile.ZipFile(zip_path) as archive:<br>        csv_members = [<br>            info for info in archive.infolist()<br>            if (not info.is_dir()) and info.filename.lower().endswith(&quot;.csv&quot;)<br>        ]<br><br>        if not csv_members:<br>            print(f&quot;[warn] No CSV entries found in ZIP: {zip_path.name}&quot;)<br>            return extracted_paths<br><br>        tasks: list[tuple[zipfile.ZipInfo, Path]] = []<br>        for info in csv_members:<br>            out_name = Path(info.filename).name<br>            target = output_dir / out_name<br>            if target.exists() and not overwrite:<br>                print(f&quot;[skip] CSV already exists: {target.name}&quot;)<br>                continue<br>            tasks.append((info, target))<br><br>        if not tasks:<br>            return extracted_paths<br><br>        total_uncompressed = sum(info.file_size for info, _ in tasks)<br>        ensure_free_space(output_dir, total_uncompressed)<br><br>        progress = ProgressBar(label=f&quot;extract:{zip_path.name}&quot;, total=total_uncompressed)<br>        progress.set(0, force=True)<br><br>        done = 0<br>        for info, target in tasks:<br>            target.parent.mkdir(parents=True, exist_ok=True)<br>            with archive.open(info, &quot;r&quot;) as src, target.open(&quot;wb&quot;) as dst:<br>                while True:<br>                    chunk = src.read(chunk_size)<br>                    if not chunk:<br>                        break<br>                    dst.write(chunk)<br>                    done += len(chunk)<br>                    progress.set(done)<br>            extracted_paths.append(target)<br><br>        progress.close()<br><br>    return extracted_paths<br><br><br>def verify_project_inputs(public_raw_dir: Path) -&gt; dict[str, bool]:<br>    status: dict[str, bool] = {}<br>    for key, pattern in PROJECT_REQUIRED_PATTERNS.items():<br>        matches = list(public_raw_dir.glob(pattern))<br>        status[key] = len(matches) &gt; 0<br>    return status<br><br><br>def print_csv_sample(path: Path, rows: int = 3) -&gt; None:<br>    print(f&quot;[sample] file={path.name}&quot;)<br>    printed = 0<br>    with path.open(&quot;r&quot;, encoding=&quot;utf-8&quot;, errors=&quot;replace&quot;) as handle:<br>        for line in handle:<br>            print(f&quot;[sample] {line.rstrip()}&quot;)<br>            printed += 1<br>            if printed &gt;= rows + 1:<br>                break<br>    if printed == 0:<br>        print(&quot;[sample] &lt;empty file&gt;&quot;)<br><br><br>def log_public_raw_samples(public_raw_dir: Path) -&gt; None:<br>    print(&quot;\n[sample] public_raw incoming/outgoing preview:&quot;)<br>    for key, pattern in PROJECT_REQUIRED_PATTERNS.items():<br>        matches = sorted(public_raw_dir.glob(pattern))<br>        if not matches:<br>            print(f&quot;[sample] {key}: missing&quot;)<br>            continue<br>        print_csv_sample(matches[0], rows=3)<br><br><br>def has_desynpuf_claim_inputs(status: dict[str, bool]) -&gt; bool:<br>    required_claim_keys = [<br>        &quot;beneficiary_csv&quot;,<br>        &quot;inpatient_claims_csv&quot;,<br>        &quot;outpatient_claims_csv&quot;,<br>        &quot;carrier_claims_csv&quot;,<br>    ]<br>    return all(status.get(key, False) for key in required_claim_keys)<br><br><br>def ensure_hospital_general_information(<br>    session: requests.Session,<br>    public_raw_dir: Path,<br>    chunk_size: int,<br>    overwrite: bool,<br>) -&gt; Path:<br>    target = public_raw_dir / &quot;hospital_general_information.csv&quot;<br>    if target.exists() and not overwrite:<br>        print(f&quot;[skip] Already present: {target.name}&quot;)<br>        return target<br><br>    downloaded = download_file(<br>        session=session,<br>        url=HOSPITAL_GENERAL_INFO_URL,<br>        temp_dir=public_raw_dir,<br>        chunk_size=chunk_size,<br>        overwrite=overwrite,<br>    )<br><br>    if downloaded.resolve() != target.resolve():<br>        if target.exists():<br>            target.unlink()<br>        downloaded.replace(target)<br><br>    print(f&quot;[info] Downloaded external file: {target.name}&quot;)<br>    return target<br><br><br>def discover_nppes_zip_url(/service/session: requests.Session) -&gt; str:<br>    response = session.get(NPPES_FILES_PAGE_URL, timeout=(15, 90))<br>    response.raise_for_status()<br><br>    links = extract_links(NPPES_FILES_PAGE_URL, response.text)<br>    zip_links = [url for url in links if looks_like_zip(url)]<br>    if not zip_links:<br>        raise RuntimeError(f&quot;No ZIP links found on NPPES page: {NPPES_FILES_PAGE_URL}&quot;)<br><br>    candidates: list[str] = []<br>    for url in zip_links:<br>        name = filename_from_https://medium.com/url(url).lower()<br>        if &quot;dissemination&quot; not in name:<br>            continue<br>        if any(hint in name for hint in NPPES_EXCLUDE_HINTS):<br>            continue<br>        candidates.append(url)<br><br>    if candidates:<br>        return candidates[0]<br>    return zip_links[0]<br><br><br>def extract_nppes_csv_from_zip(<br>    zip_path: Path,<br>    target_csv: Path,<br>    chunk_size: int,<br>    overwrite: bool,<br>) -&gt; Path:<br>    if target_csv.exists() and not overwrite:<br>        print(f&quot;[skip] Already present: {target_csv.name}&quot;)<br>        return target_csv<br><br>    with zipfile.ZipFile(zip_path) as archive:<br>        csv_members = [<br>            info for info in archive.infolist()<br>            if (not info.is_dir()) and info.filename.lower().endswith(&quot;.csv&quot;)<br>        ]<br>        if not csv_members:<br>            raise RuntimeError(f&quot;No CSV entries found in NPPES zip: {zip_path.name}&quot;)<br><br>        preferred: list[zipfile.ZipInfo] = []<br>        fallback: list[zipfile.ZipInfo] = []<br>        for info in csv_members:<br>            base = Path(info.filename).name.lower()<br>            if &quot;npidata&quot; in base and &quot;othername&quot; not in base and &quot;endpoint&quot; not in base and &quot;pl_pfile&quot; not in base:<br>                preferred.append(info)<br>            else:<br>                fallback.append(info)<br><br>        selected = preferred[0] if preferred else csv_members[0]<br>        target_csv.parent.mkdir(parents=True, exist_ok=True)<br>        ensure_free_space(target_csv.parent, selected.file_size)<br><br>        progress = ProgressBar(label=f&quot;extract:{zip_path.name}&quot;, total=selected.file_size)<br>        progress.set(0, force=True)<br><br>        done = 0<br>        with archive.open(selected, &quot;r&quot;) as src, target_csv.open(&quot;wb&quot;) as dst:<br>            while True:<br>                chunk = src.read(chunk_size)<br>                if not chunk:<br>                    break<br>                dst.write(chunk)<br>                done += len(chunk)<br>                progress.set(done)<br><br>        progress.close()<br><br>    return target_csv<br><br><br>def ensure_nppes_csv(<br>    session: requests.Session,<br>    temp_dir: Path,<br>    public_raw_dir: Path,<br>    chunk_size: int,<br>    overwrite: bool,<br>    keep_zips: bool,<br>) -&gt; Path:<br>    target = public_raw_dir / &quot;nppes.csv&quot;<br>    if target.exists() and not overwrite:<br>        print(f&quot;[skip] Already present: {target.name}&quot;)<br>        return target<br><br>    print(f&quot;[info] Discovering NPPES monthly download from: {NPPES_FILES_PAGE_URL}&quot;)<br>    nppes_zip_url = discover_nppes_zip_url(https://medium.com/session)<br>    print(f&quot;[info] NPPES ZIP selected: {nppes_zip_url}&quot;)<br><br>    zip_file = download_file(<br>        session=session,<br>        url=nppes_zip_url,<br>        temp_dir=temp_dir,<br>        chunk_size=chunk_size,<br>        overwrite=overwrite,<br>    )<br>    extract_nppes_csv_from_zip(<br>        zip_path=zip_file,<br>        target_csv=target,<br>        chunk_size=chunk_size,<br>        overwrite=overwrite,<br>    )<br>    print(f&quot;[info] Extracted external file: {target.name}&quot;)<br><br>    if not keep_zips:<br>        zip_file.unlink(missing_ok=True)<br><br>    return target<br><br><br>def parse_args() -&gt; argparse.Namespace:<br>    parser = argparse.ArgumentParser(<br>        description=(<br>            &quot;Download required CMS DE-SynPUF (sample 1) ZIP files to temp and extract CSV files into data/public_raw.&quot;<br>        )<br>    )<br>    parser.add_argument(<br>        &quot;--cms-page-url&quot;,<br>        default=CMS_PAGE_URL,<br>        help=&quot;CMS page used to discover ZIP links.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--url&quot;,<br>        action=&quot;append&quot;,<br>        default=[],<br>        help=&quot;Explicit ZIP URL(s). Can be provided multiple times.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--temp-dir&quot;,<br>        default=&quot;./temp/public_raw_downloads&quot;,<br>        help=&quot;Temporary folder for ZIP downloads.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--public-raw-dir&quot;,<br>        default=&quot;./data/public_raw&quot;,<br>        help=&quot;Destination folder for extracted CSV files.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--chunk-size-mb&quot;,<br>        type=int,<br>        default=8,<br>        help=&quot;Streaming chunk size in MB for download and extraction.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--overwrite&quot;,<br>        action=&quot;store_true&quot;,<br>        help=&quot;Overwrite existing ZIP/CSV outputs.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--keep-zips&quot;,<br>        action=&quot;store_true&quot;,<br>        help=&quot;Keep ZIP files in temp-dir after extraction.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--dry-run&quot;,<br>        action=&quot;store_true&quot;,<br>        help=&quot;Only print URLs that would be downloaded.&quot;,<br>    )<br>    return parser.parse_args()<br><br><br>def main() -&gt; int:<br>    args = parse_args()<br><br>    temp_dir = Path(args.temp_dir).resolve()<br>    public_raw_dir = Path(args.public_raw_dir).resolve()<br>    temp_dir.mkdir(parents=True, exist_ok=True)<br>    public_raw_dir.mkdir(parents=True, exist_ok=True)<br><br>    chunk_size = int(args.chunk_size_mb) * 1024 * 1024<br>    if chunk_size &lt;= 0:<br>        raise ValueError(&quot;--chunk-size-mb must be &gt; 0&quot;)<br><br>    session = build_session()<br>    explicit_urls = unique(args.url)<br>    initial_status = verify_project_inputs(public_raw_dir)<br><br>    zip_urls: list[str] = []<br>    if explicit_urls:<br>        zip_urls = explicit_urls<br>    elif args.overwrite or not has_desynpuf_claim_inputs(initial_status):<br>        print(f&quot;[info] Discovering ZIP links from: {args.cms_page_url}&quot;)<br>        discovered = discover_zip_urls(session, args.cms_page_url)<br>        if not discovered:<br>            raise RuntimeError(<br>                &quot;No ZIP links discovered from CMS page. &quot;<br>                &quot;Pass direct links using --url as fallback.&quot;<br>            )<br>        zip_urls = select_required_cms_urls(discovered)<br>    else:<br>        print(&quot;[info] Required DE-SynPUF claim CSVs already present. Skipping ZIP download.&quot;)<br><br>    if zip_urls:<br>        print(f&quot;[info] ZIP files selected: {len(zip_urls)}&quot;)<br>        for idx, url in enumerate(zip_urls, start=1):<br>            print(f&quot;  {idx:02d}. {url}&quot;)<br><br>    if args.dry_run:<br>        return 0<br><br>    for url in zip_urls:<br>        zip_file = download_file(<br>            session=session,<br>            url=url,<br>            temp_dir=temp_dir,<br>            chunk_size=chunk_size,<br>            overwrite=args.overwrite,<br>        )<br>        extracted = extract_zip(<br>            zip_path=zip_file,<br>            output_dir=public_raw_dir,<br>            chunk_size=chunk_size,<br>            overwrite=args.overwrite,<br>        )<br>        print(f&quot;[info] Extracted {len(extracted)} CSV file(s) from {zip_file.name}&quot;)<br>        if not args.keep_zips:<br>            zip_file.unlink(missing_ok=True)<br><br>    status_after_claims = verify_project_inputs(public_raw_dir)<br>    if args.overwrite or not status_after_claims[&quot;nppes_csv&quot;]:<br>        ensure_nppes_csv(<br>            session=session,<br>            temp_dir=temp_dir,<br>            public_raw_dir=public_raw_dir,<br>            chunk_size=chunk_size,<br>            overwrite=args.overwrite,<br>            keep_zips=args.keep_zips,<br>        )<br><br>    status_after_nppes = verify_project_inputs(public_raw_dir)<br>    if args.overwrite or not status_after_nppes[&quot;hospital_general_information_csv&quot;]:<br>        ensure_hospital_general_information(<br>            session=session,<br>            public_raw_dir=public_raw_dir,<br>            chunk_size=chunk_size,<br>            overwrite=args.overwrite,<br>        )<br><br>    status = verify_project_inputs(public_raw_dir)<br>    print(&quot;\n[summary] data/public_raw availability:&quot;)<br>    for key in sorted(status):<br>        marker = &quot;OK&quot; if status[key] else &quot;MISSING&quot;<br>        print(f&quot;  - {key}: {marker}&quot;)<br><br>    missing_external: list[str] = []<br>    if not status[&quot;nppes_csv&quot;]:<br>        missing_external.append(&quot;nppes.csv&quot;)<br>    if not status[&quot;hospital_general_information_csv&quot;]:<br>        missing_external.append(&quot;hospital_general_information.csv&quot;)<br><br>    if missing_external:<br>        print(<br>            &quot;\n[notice] Missing external source file(s): &quot;<br>            + &quot;, &quot;.join(missing_external)<br>            + &quot;.&quot;<br>        )<br>        if &quot;nppes.csv&quot; in missing_external:<br>            print(&quot;[notice] NPPES source: https://download.cms.gov/nppes/&quot;)<br>        if &quot;hospital_general_information.csv&quot; in missing_external:<br>            print(f&quot;[notice] Hospital General Information direct URL: {HOSPITAL_GENERAL_INFO_URL}&quot;)<br><br>    log_public_raw_samples(public_raw_dir)<br><br>    return 0<br><br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><ul><li>Seed builder: apps/simulation/seed_public_data.py</li></ul><pre>import argparse<br>import glob<br>import logging<br>from pathlib import Path<br>from typing import Callable<br><br>import numpy as np<br>import pandas as pd<br>import yaml<br><br>logger = logging.getLogger(__name__)<br><br>BENEFICIARY_COLUMNS = {<br>    &quot;DESYNPUF_ID&quot;,<br>    &quot;SP_STATE_CODE&quot;,<br>    &quot;BENE_SEX_IDENT_CD&quot;,<br>    &quot;BENE_RACE_CD&quot;,<br>}<br><br>INSTITUTIONAL_COLUMNS = {<br>    &quot;DESYNPUF_ID&quot;,<br>    &quot;CLM_ID&quot;,<br>    &quot;CLM_FROM_DT&quot;,<br>    &quot;CLM_THRU_DT&quot;,<br>    &quot;PRVDR_NUM&quot;,<br>    &quot;AT_PHYSN_NPI&quot;,<br>    &quot;OP_PHYSN_NPI&quot;,<br>    &quot;OT_PHYSN_NPI&quot;,<br>    &quot;CLM_PMT_AMT&quot;,<br>    &quot;NCH_PRMRY_PYR_CLM_PD_AMT&quot;,<br>    &quot;HCPCS_CD_1&quot;,<br>}<br><br>CARRIER_BASE_COLUMNS = {<br>    &quot;DESYNPUF_ID&quot;,<br>    &quot;CLM_ID&quot;,<br>    &quot;CLM_FROM_DT&quot;,<br>    &quot;CLM_THRU_DT&quot;,<br>}<br>CARRIER_PREFIX_COLUMNS = (<br>    &quot;PRF_PHYSN_NPI_&quot;,<br>    &quot;HCPCS_CD_&quot;,<br>    &quot;LINE_NCH_PMT_AMT_&quot;,<br>    &quot;TAX_NUM_&quot;,<br>)<br><br>NPPES_SOURCE_COLUMNS = {<br>    &quot;NPI&quot;,<br>    &quot;Provider Organization Name (Legal Business Name)&quot;,<br>    &quot;Provider Last Name (Legal Name)&quot;,<br>    &quot;Provider First Name&quot;,<br>    &quot;Healthcare Provider Taxonomy Code_1&quot;,<br>    &quot;Healthcare Provider Taxonomy Code&quot;,<br>    &quot;Healthcare Provider Primary Taxonomy Switch_1&quot;,<br>    &quot;Healthcare Provider Primary Taxonomy Switch&quot;,<br>    &quot;Provider Business Practice Location Address City Name&quot;,<br>    &quot;Provider Business Practice Location Address State Name&quot;,<br>    &quot;Provider Business Practice Location Address Postal Code&quot;,<br>}<br><br><br>def configure_logging() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br><br><br>def log_sample_df(label: str, df: pd.DataFrame, rows: int = 3) -&gt; None:<br>    logger.info(&quot;[%s] Sample rows (showing up to %d)&quot;, label, rows)<br>    if df.empty:<br>        logger.info(&quot;[%s] &lt;empty dataframe&gt;&quot;, label)<br>        return<br>    sample = df.head(rows).to_string(index=False)<br>    for line in sample.splitlines():<br>        logger.info(&quot;[%s] %s&quot;, label, line)<br><br><br>def random_state(rng: np.random.Generator) -&gt; int:<br>    return int(rng.integers(0, np.iinfo(np.int32).max))<br><br><br>def matched_files(pattern: str) -&gt; list[str]:<br>    files = sorted(glob.glob(pattern))<br>    if not files:<br>        raise FileNotFoundError(f&quot;No files matched pattern: {pattern}&quot;)<br>    return files<br><br><br>def normalize_id_values(series: pd.Series) -&gt; pd.Series:<br>    return (<br>        series.astype(str)<br>        .str.strip()<br>        .str.replace(&quot;.0&quot;, &quot;&quot;, regex=False)<br>        .replace({&quot;nan&quot;: None, &quot;None&quot;: None, &quot;&quot;: None})<br>    )<br><br><br>def normalize_npi_values(series: pd.Series) -&gt; pd.Series:<br>    normalized = normalize_id_values(series)<br>    digits = normalized.fillna(&quot;&quot;).str.replace(r&quot;\D+&quot;, &quot;&quot;, regex=True)<br>    digits = digits.where(digits.str.len() &gt; 0, None)<br>    digits = digits.where(digits.str.len() &lt;= 10, None)<br>    return digits.where(digits.isna(), digits.str.zfill(10))<br><br><br>def first_existing(df: pd.DataFrame, candidates: list[str], default=None):<br>    for col in candidates:<br>        if col in df.columns:<br>            return df[col]<br>    if default is None:<br>        return pd.Series([None] * len(df))<br>    return pd.Series([default] * len(df))<br><br><br>def to_date(series: pd.Series) -&gt; pd.Series:<br>    s = series.astype(str).str.replace(&quot;.0&quot;, &quot;&quot;, regex=False)<br>    parsed = pd.to_datetime(s, errors=&quot;coerce&quot;, format=&quot;%Y%m%d&quot;)<br>    missing = parsed.isna()<br>    if missing.any():<br>        parsed.loc[missing] = pd.to_datetime(s.loc[missing], errors=&quot;coerce&quot;)<br>    return parsed<br><br><br>def normalize_institutional(df: pd.DataFrame, claim_type: str) -&gt; pd.DataFrame:<br>    out = pd.DataFrame()<br>    out[&quot;patient_id&quot;] = normalize_id_values(df[&quot;DESYNPUF_ID&quot;])<br>    out[&quot;claim_id&quot;] = normalize_id_values(df[&quot;CLM_ID&quot;])<br>    out[&quot;claim_type&quot;] = claim_type<br>    out[&quot;service_from_date&quot;] = to_date(df[&quot;CLM_FROM_DT&quot;])<br>    out[&quot;service_thru_date&quot;] = to_date(df[&quot;CLM_THRU_DT&quot;])<br>    out[&quot;facility_id&quot;] = normalize_id_values(first_existing(df, [&quot;PRVDR_NUM&quot;]))<br>    primary_npi = normalize_npi_values(first_existing(df, [&quot;AT_PHYSN_NPI&quot;]))<br>    secondary_npi = normalize_npi_values(first_existing(df, [&quot;OP_PHYSN_NPI&quot;]))<br>    tertiary_npi = normalize_npi_values(first_existing(df, [&quot;OT_PHYSN_NPI&quot;]))<br>    out[&quot;provider_npi&quot;] = primary_npi.fillna(secondary_npi).fillna(tertiary_npi)<br>    out[&quot;paid_amount&quot;] = pd.to_numeric(df[&quot;CLM_PMT_AMT&quot;], errors=&quot;coerce&quot;).fillna(0.0)<br>    out[&quot;primary_payer_paid_amount&quot;] = pd.to_numeric(<br>        first_existing(df, [&quot;NCH_PRMRY_PYR_CLM_PD_AMT&quot;], 0.0), errors=&quot;coerce&quot;<br>    ).fillna(0.0)<br>    out[&quot;procedure_code&quot;] = first_existing(df, [&quot;HCPCS_CD_1&quot;]).astype(str).replace({&quot;nan&quot;: None})<br>    return out<br><br><br>def normalize_carrier(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    out = pd.DataFrame()<br>    out[&quot;patient_id&quot;] = normalize_id_values(df[&quot;DESYNPUF_ID&quot;])<br>    out[&quot;claim_id&quot;] = normalize_id_values(df[&quot;CLM_ID&quot;])<br>    out[&quot;claim_type&quot;] = &quot;carrier&quot;<br>    out[&quot;service_from_date&quot;] = to_date(df[&quot;CLM_FROM_DT&quot;])<br>    out[&quot;service_thru_date&quot;] = to_date(df[&quot;CLM_THRU_DT&quot;])<br><br>    npi_cols = [c for c in df.columns if c.startswith(&quot;PRF_PHYSN_NPI_&quot;)]<br>    hcpcs_cols = [c for c in df.columns if c.startswith(&quot;HCPCS_CD_&quot;)]<br>    paid_cols = [c for c in df.columns if c.startswith(&quot;LINE_NCH_PMT_AMT_&quot;)]<br>    tax_cols = [c for c in df.columns if c.startswith(&quot;TAX_NUM_&quot;)]<br><br>    out[&quot;provider_npi&quot;] = (<br>        normalize_npi_values(df[npi_cols].bfill(axis=1).iloc[:, 0])<br>        if npi_cols<br>        else pd.Series([None] * len(df), index=df.index)<br>    )<br>    out[&quot;facility_id&quot;] = (<br>        normalize_id_values(df[tax_cols].bfill(axis=1).iloc[:, 0])<br>        if tax_cols<br>        else pd.Series([None] * len(df), index=df.index)<br>    )<br>    out[&quot;procedure_code&quot;] = (<br>        df[hcpcs_cols].bfill(axis=1).iloc[:, 0].astype(str).replace({&quot;nan&quot;: None})<br>        if hcpcs_cols<br>        else None<br>    )<br>    out[&quot;paid_amount&quot;] = (<br>        df[paid_cols].apply(pd.to_numeric, errors=&quot;coerce&quot;).fillna(0.0).sum(axis=1)<br>        if paid_cols<br>        else 0.0<br>    )<br>    out[&quot;primary_payer_paid_amount&quot;] = 0.0<br>    return out<br><br><br>def normalize_nppes(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    def pick(cols: list[str]) -&gt; pd.Series:<br>        return first_existing(df, cols)<br><br>    out = pd.DataFrame()<br>    out[&quot;provider_npi&quot;] = normalize_npi_values(pick([&quot;NPI&quot;]))<br>    out[&quot;provider_name&quot;] = (<br>        pick([&quot;Provider Organization Name (Legal Business Name)&quot;])<br>        .fillna(<br>            pick([&quot;Provider Last Name (Legal Name)&quot;]).astype(str).str.cat(<br>                pick([&quot;Provider First Name&quot;]), sep=&quot;, &quot;, na_rep=&quot;&quot;<br>            )<br>        )<br>    )<br>    out[&quot;taxonomy_code&quot;] = pick(<br>        [&quot;Healthcare Provider Taxonomy Code_1&quot;, &quot;Healthcare Provider Taxonomy Code&quot;]<br>    ).astype(str)<br>    out[&quot;is_primary_taxonomy&quot;] = pick(<br>        [&quot;Healthcare Provider Primary Taxonomy Switch_1&quot;, &quot;Healthcare Provider Primary Taxonomy Switch&quot;]<br>    ).astype(str)<br>    out[&quot;city&quot;] = pick([&quot;Provider Business Practice Location Address City Name&quot;]).astype(str)<br>    out[&quot;state&quot;] = pick([&quot;Provider Business Practice Location Address State Name&quot;]).astype(str)<br>    out[&quot;zip_code&quot;] = pick([&quot;Provider Business Practice Location Address Postal Code&quot;]).astype(str)<br>    return out.drop_duplicates(subset=[&quot;provider_npi&quot;])<br><br><br>def normalize_hospital(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    out = pd.DataFrame()<br>    out[&quot;facility_id&quot;] = normalize_id_values(<br>        first_existing(df, [&quot;Facility ID&quot;, &quot;facility_id&quot;, &quot;CMS Certification Number&quot;])<br>    )<br>    out[&quot;facility_name&quot;] = first_existing(df, [&quot;Hospital Name&quot;, &quot;facility_name&quot;]).astype(str)<br>    out[&quot;state&quot;] = first_existing(df, [&quot;State&quot;, &quot;state&quot;]).astype(str)<br>    out[&quot;city&quot;] = first_existing(df, [&quot;City/Town&quot;, &quot;city&quot;]).astype(str)<br>    out[&quot;zip_code&quot;] = first_existing(df, [&quot;ZIP Code&quot;, &quot;zip_code&quot;]).astype(str)<br>    out[&quot;hospital_type&quot;] = first_existing(df, [&quot;Hospital Type&quot;, &quot;hospital_type&quot;]).astype(str)<br>    out[&quot;ownership&quot;] = first_existing(df, [&quot;Hospital Ownership&quot;, &quot;ownership&quot;]).astype(str)<br>    out[&quot;overall_rating&quot;] = first_existing(df, [&quot;Hospital overall rating&quot;, &quot;overall_rating&quot;]).astype(str)<br>    out[&quot;emergency_services&quot;] = first_existing(df, [&quot;Emergency Services&quot;, &quot;emergency_services&quot;]).astype(str)<br>    return out.drop_duplicates(subset=[&quot;facility_id&quot;])<br><br><br>def update_reservoir_sample(<br>    reservoir: pd.DataFrame,<br>    seen_rows: int,<br>    chunk: pd.DataFrame,<br>    sample_size: int,<br>    rng: np.random.Generator,<br>) -&gt; tuple[pd.DataFrame, int]:<br>    if chunk.empty:<br>        return reservoir, seen_rows<br><br>    chunk_rows = len(chunk)<br>    total_rows = seen_rows + chunk_rows<br>    target_size = min(sample_size, total_rows)<br><br>    if target_size == total_rows:<br>        updated = pd.concat([reservoir, chunk], ignore_index=True)<br>        return updated, total_rows<br><br>    draw_new = int(<br>        rng.hypergeometric(<br>            ngood=chunk_rows,<br>            nbad=seen_rows,<br>            nsample=target_size,<br>        )<br>    )<br>    draw_old = target_size - draw_new<br><br>    old_sample = (<br>        reservoir.sample(n=draw_old, random_state=random_state(rng))<br>        if draw_old &gt; 0<br>        else reservoir.iloc[0:0]<br>    )<br>    new_sample = (<br>        chunk.sample(n=draw_new, random_state=random_state(rng))<br>        if draw_new &gt; 0<br>        else chunk.iloc[0:0]<br>    )<br><br>    updated = pd.concat([old_sample, new_sample], ignore_index=True)<br>    return updated, total_rows<br><br><br>def sample_claims_from_glob(<br>    pattern: str,<br>    sample_size: int,<br>    chunksize: int,<br>    log_every_chunks: int,<br>    max_scan_rows: int | None,<br>    rng: np.random.Generator,<br>    usecols: Callable[[str], bool] | list[str] | None,<br>    normalize_fn: Callable[[pd.DataFrame], pd.DataFrame],<br>    label: str,<br>) -&gt; pd.DataFrame:<br>    files = matched_files(pattern)<br>    logger.info(&quot;[%s] Found %d file(s) for %s&quot;, label, len(files), pattern)<br><br>    reservoir = pd.DataFrame()<br>    seen_rows = 0<br><br>    for file_path in files:<br>        logger.info(&quot;[%s] Reading file: %s&quot;, label, file_path)<br>        for chunk_idx, chunk in enumerate(<br>            pd.read_csv(file_path, usecols=usecols, low_memory=False, chunksize=chunksize),<br>            start=1,<br>        ):<br>            normalized = normalize_fn(chunk)<br>            reservoir, seen_rows = update_reservoir_sample(<br>                reservoir=reservoir,<br>                seen_rows=seen_rows,<br>                chunk=normalized,<br>                sample_size=sample_size,<br>                rng=rng,<br>            )<br><br>            if chunk_idx == 1 or chunk_idx % log_every_chunks == 0:<br>                logger.info(<br>                    &quot;[%s] chunks=%d | seen_rows=%d | sampled_rows=%d&quot;,<br>                    label,<br>                    chunk_idx,<br>                    seen_rows,<br>                    len(reservoir),<br>                )<br>            if max_scan_rows is not None and seen_rows &gt;= max_scan_rows:<br>                logger.info(<br>                    &quot;[%s] Reached max_scan_rows=%d; stopping early&quot;,<br>                    label,<br>                    max_scan_rows,<br>                )<br>                logger.info(<br>                    &quot;[%s] Early-stop sample | seen_rows=%d | final_sampled_rows=%d&quot;,<br>                    label,<br>                    seen_rows,<br>                    len(reservoir),<br>                )<br>                return reservoir<br><br>    logger.info(<br>        &quot;[%s] Completed sampling | seen_rows=%d | final_sampled_rows=%d&quot;,<br>        label,<br>        seen_rows,<br>        len(reservoir),<br>    )<br>    return reservoir<br><br><br>def carrier_usecols(column: str) -&gt; bool:<br>    return column in CARRIER_BASE_COLUMNS or column.startswith(CARRIER_PREFIX_COLUMNS)<br><br><br>def load_beneficiary_for_patient_ids(<br>    pattern: str,<br>    patient_ids: set[str],<br>    chunksize: int,<br>    log_every_chunks: int,<br>) -&gt; pd.DataFrame:<br>    if not patient_ids:<br>        logger.warning(&quot;No patient IDs in sampled claims; beneficiary enrichment will be empty&quot;)<br>        return pd.DataFrame(columns=[&quot;patient_id&quot;, &quot;patient_state&quot;, &quot;sex_code&quot;, &quot;race_code&quot;])<br><br>    files = matched_files(pattern)<br>    logger.info(&quot;[beneficiary] Found %d file(s) for %s&quot;, len(files), pattern)<br><br>    frames: list[pd.DataFrame] = []<br>    seen_rows = 0<br>    kept_rows = 0<br>    chunk_counter = 0<br>    for file_path in files:<br>        logger.info(&quot;[beneficiary] Reading file: %s&quot;, file_path)<br>        for chunk in pd.read_csv(<br>            file_path,<br>            usecols=lambda c: c in BENEFICIARY_COLUMNS,<br>            low_memory=False,<br>            chunksize=chunksize,<br>        ):<br>            chunk_counter += 1<br>            seen_rows += len(chunk)<br>            chunk_ids = normalize_id_values(chunk[&quot;DESYNPUF_ID&quot;])<br>            filtered = chunk.loc[chunk_ids.isin(patient_ids)].copy()<br>            if not filtered.empty:<br>                filtered[&quot;DESYNPUF_ID&quot;] = normalize_id_values(filtered[&quot;DESYNPUF_ID&quot;])<br>                frames.append(filtered)<br>                kept_rows += len(filtered)<br>            if chunk_counter == 1 or chunk_counter % log_every_chunks == 0:<br>                logger.info(<br>                    &quot;[beneficiary] chunks=%d | seen_rows=%d | kept_rows=%d&quot;,<br>                    chunk_counter,<br>                    seen_rows,<br>                    kept_rows,<br>                )<br><br>    beneficiary = (<br>        pd.concat(frames, ignore_index=True)<br>        if frames<br>        else pd.DataFrame(columns=list(BENEFICIARY_COLUMNS))<br>    )<br>    bene = pd.DataFrame(<br>        {<br>            &quot;patient_id&quot;: normalize_id_values(first_existing(beneficiary, [&quot;DESYNPUF_ID&quot;])),<br>            &quot;patient_state&quot;: first_existing(beneficiary, [&quot;SP_STATE_CODE&quot;]).astype(str),<br>            &quot;sex_code&quot;: first_existing(beneficiary, [&quot;BENE_SEX_IDENT_CD&quot;]).astype(str),<br>            &quot;race_code&quot;: first_existing(beneficiary, [&quot;BENE_RACE_CD&quot;]).astype(str),<br>        }<br>    ).drop_duplicates(subset=[&quot;patient_id&quot;])<br><br>    logger.info(<br>        &quot;[beneficiary] Completed lookup | seen_rows=%d | matched_rows=%d | unique_patients=%d&quot;,<br>        seen_rows,<br>        kept_rows,<br>        len(bene),<br>    )<br>    return bene<br><br><br>def build_nppes_fallback_rows(provider_npis: set[str]) -&gt; pd.DataFrame:<br>    if not provider_npis:<br>        return pd.DataFrame(<br>            columns=[<br>                &quot;provider_npi&quot;,<br>                &quot;provider_name&quot;,<br>                &quot;taxonomy_code&quot;,<br>                &quot;is_primary_taxonomy&quot;,<br>                &quot;city&quot;,<br>                &quot;state&quot;,<br>                &quot;zip_code&quot;,<br>            ]<br>        )<br>    return pd.DataFrame(<br>        {<br>            &quot;provider_npi&quot;: sorted(provider_npis),<br>            &quot;provider_name&quot;: &quot;Unknown Provider&quot;,<br>            &quot;taxonomy_code&quot;: None,<br>            &quot;is_primary_taxonomy&quot;: None,<br>            &quot;city&quot;: None,<br>            &quot;state&quot;: None,<br>            &quot;zip_code&quot;: None,<br>        }<br>    )<br><br><br>def load_nppes_for_provider_npis(<br>    file_path: str,<br>    provider_npis: set[str],<br>    chunksize: int,<br>    log_every_chunks: int,<br>    max_scan_rows: int | None,<br>) -&gt; pd.DataFrame:<br>    if not provider_npis:<br>        logger.warning(&quot;No provider NPIs in sampled claims; providers reference will be empty&quot;)<br>        return build_nppes_fallback_rows(set())<br><br>    logger.info(&quot;[nppes] Loading provider reference for %d provider NPI(s)&quot;, len(provider_npis))<br><br>    frames: list[pd.DataFrame] = []<br>    seen_rows = 0<br>    kept_rows = 0<br>    remaining_npis = set(provider_npis)<br>    requested_prefixes = {npi[:9] for npi in provider_npis if len(npi) == 10}<br>    prefix_to_npis: dict[str, set[str]] = {}<br>    npi_to_row: dict[str, dict[str, str | None]] = {}<br>    for chunk_idx, chunk in enumerate(<br>        pd.read_csv(<br>            file_path,<br>            usecols=lambda c: c in NPPES_SOURCE_COLUMNS,<br>            low_memory=False,<br>            chunksize=chunksize,<br>        ),<br>        start=1,<br>    ):<br>        seen_rows += len(chunk)<br>        normalized = normalize_nppes(chunk)<br>        filtered = normalized[normalized[&quot;provider_npi&quot;].isin(provider_npis)].copy()<br>        if not filtered.empty:<br>            frames.append(filtered)<br>            kept_rows += len(filtered)<br>            matched_in_chunk = set(filtered[&quot;provider_npi&quot;].dropna().astype(str))<br>            remaining_npis -= matched_in_chunk<br><br>        if requested_prefixes:<br>            prefix_candidates = normalized[<br>                normalized[&quot;provider_npi&quot;].fillna(&quot;&quot;).str.len() == 10<br>            ].copy()<br>            if not prefix_candidates.empty:<br>                prefix_candidates[&quot;prefix9&quot;] = prefix_candidates[&quot;provider_npi&quot;].str[:9]<br>                prefix_candidates = prefix_candidates[<br>                    prefix_candidates[&quot;prefix9&quot;].isin(requested_prefixes)<br>                ]<br>                for row in prefix_candidates.itertuples(index=False):<br>                    provider_npi = row.provider_npi<br>                    prefix9 = row.prefix9<br>                    if not provider_npi or not prefix9:<br>                        continue<br>                    prefix_bucket = prefix_to_npis.setdefault(prefix9, set())<br>                    if len(prefix_bucket) &lt; 2:<br>                        prefix_bucket.add(provider_npi)<br>                    if provider_npi not in npi_to_row:<br>                        npi_to_row[provider_npi] = {<br>                            &quot;provider_npi&quot;: provider_npi,<br>                            &quot;provider_name&quot;: row.provider_name,<br>                            &quot;taxonomy_code&quot;: row.taxonomy_code,<br>                            &quot;is_primary_taxonomy&quot;: row.is_primary_taxonomy,<br>                            &quot;city&quot;: row.city,<br>                            &quot;state&quot;: row.state,<br>                            &quot;zip_code&quot;: row.zip_code,<br>                        }<br><br>        if chunk_idx == 1 or chunk_idx % log_every_chunks == 0:<br>            logger.info(<br>                &quot;[nppes] chunks=%d | seen_rows=%d | matched_rows=%d | remaining_npis=%d&quot;,<br>                chunk_idx,<br>                seen_rows,<br>                kept_rows,<br>                len(remaining_npis),<br>            )<br>        if not remaining_npis:<br>            logger.info(&quot;[nppes] All required provider NPIs found; stopping early&quot;)<br>            break<br>        if max_scan_rows is not None and seen_rows &gt;= max_scan_rows:<br>            logger.warning(<br>                &quot;[nppes] Reached max_scan_rows=%d before full match; using fallback for missing NPIs&quot;,<br>                max_scan_rows,<br>            )<br>            break<br><br>    providers = (<br>        pd.concat(frames, ignore_index=True).drop_duplicates(subset=[&quot;provider_npi&quot;])<br>        if frames<br>        else build_nppes_fallback_rows(set())<br>    )<br><br>    matched_npis = set(providers[&quot;provider_npi&quot;].dropna().astype(str))<br>    missing = provider_npis - matched_npis<br>    prefix9_resolved = 0<br>    if missing:<br>        prefix_rows: list[dict[str, str | None]] = []<br>        for missing_npi in sorted(missing):<br>            if len(missing_npi) != 10:<br>                continue<br>            candidates = prefix_to_npis.get(missing_npi[:9], set())<br>            if len(candidates) != 1:<br>                continue<br>            matched_npi = next(iter(candidates))<br>            matched_row = npi_to_row.get(matched_npi)<br>            if not matched_row:<br>                continue<br>            row_copy = dict(matched_row)<br>            row_copy[&quot;provider_npi&quot;] = missing_npi<br>            prefix_rows.append(row_copy)<br><br>        if prefix_rows:<br>            providers = pd.concat(<br>                [providers, pd.DataFrame(prefix_rows)],<br>                ignore_index=True,<br>            ).drop_duplicates(subset=[&quot;provider_npi&quot;])<br>            matched_npis = set(providers[&quot;provider_npi&quot;].dropna().astype(str))<br>            missing = provider_npis - matched_npis<br>            prefix9_resolved = len(prefix_rows)<br>            logger.info(<br>                &quot;[nppes] Prefix-9 fallback resolved %d provider NPI(s) with unique base match&quot;,<br>                prefix9_resolved,<br>            )<br><br>    matched_count = len(provider_npis) - len(missing)<br>    if missing:<br>        logger.warning(<br>            &quot;[nppes] Missing %d provider NPI(s) in NPPES; adding synthetic fallback rows&quot;,<br>            len(missing),<br>        )<br>        providers = pd.concat(<br>            [providers, build_nppes_fallback_rows(missing)],<br>            ignore_index=True,<br>        ).drop_duplicates(subset=[&quot;provider_npi&quot;])<br><br>    logger.info(<br>        &quot;[nppes] Completed lookup | seen_rows=%d | matched_rows=%d | output_rows=%d | matched_provider_npis=%d/%d (%.2f%%)&quot;,<br>        seen_rows,<br>        kept_rows,<br>        len(providers),<br>        matched_count,<br>        len(provider_npis),<br>        (matched_count / len(provider_npis) * 100.0) if provider_npis else 0.0,<br>    )<br>    if prefix9_resolved &gt; 0:<br>        logger.info(<br>            &quot;[nppes] Match uplift from prefix-9 fallback: +%d provider NPI(s)&quot;,<br>            prefix9_resolved,<br>        )<br>    return providers<br><br><br>def main():<br>    configure_logging()<br><br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--config&quot;, required=True)<br>    args = parser.parse_args()<br><br>    with open(args.config, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        cfg = yaml.safe_load(f)<br><br>    output_dir = Path(cfg[&quot;output_dir&quot;])<br>    output_dir.mkdir(parents=True, exist_ok=True)<br><br>    sample_size = int(cfg.get(&quot;sample_size_per_claim_type&quot;, 50000))<br>    chunksize = int(cfg.get(&quot;chunksize&quot;, 100000))<br>    log_every_chunks = int(cfg.get(&quot;log_every_chunks&quot;, 10))<br>    raw_max_scan_rows_per_claim_type = cfg.get(&quot;max_scan_rows_per_claim_type&quot;)<br>    raw_nppes_max_scan_rows = cfg.get(&quot;nppes_max_scan_rows&quot;)<br>    max_scan_rows_per_claim_type = (<br>        int(raw_max_scan_rows_per_claim_type)<br>        if raw_max_scan_rows_per_claim_type is not None<br>        else None<br>    )<br>    nppes_max_scan_rows = (<br>        int(raw_nppes_max_scan_rows)<br>        if raw_nppes_max_scan_rows is not None<br>        else None<br>    )<br>    if sample_size &lt;= 0 or chunksize &lt;= 0 or log_every_chunks &lt;= 0:<br>        raise ValueError(<br>            &quot;sample_size_per_claim_type, chunksize, and log_every_chunks must be &gt; 0&quot;<br>        )<br>    if max_scan_rows_per_claim_type is not None and max_scan_rows_per_claim_type &lt;= 0:<br>        raise ValueError(&quot;max_scan_rows_per_claim_type must be &gt; 0&quot;)<br>    if nppes_max_scan_rows is not None and nppes_max_scan_rows &lt;= 0:<br>        raise ValueError(&quot;nppes_max_scan_rows must be &gt; 0&quot;)<br><br>    rng = np.random.default_rng(42)<br>    logger.info(<br>        &quot;Starting seed build | sample_size=%d | chunksize=%d | log_every_chunks=%d | max_scan_rows_per_claim_type=%s | nppes_max_scan_rows=%s&quot;,<br>        sample_size,<br>        chunksize,<br>        log_every_chunks,<br>        &quot;full_scan&quot; if max_scan_rows_per_claim_type is None else str(max_scan_rows_per_claim_type),<br>        &quot;full_scan&quot; if nppes_max_scan_rows is None else str(nppes_max_scan_rows),<br>    )<br><br>    inpatient = sample_claims_from_glob(<br>        pattern=cfg[&quot;inpatient_glob&quot;],<br>        sample_size=sample_size,<br>        chunksize=chunksize,<br>        log_every_chunks=log_every_chunks,<br>        max_scan_rows=max_scan_rows_per_claim_type,<br>        rng=rng,<br>        usecols=lambda c: c in INSTITUTIONAL_COLUMNS,<br>        normalize_fn=lambda df: normalize_institutional(df, &quot;inpatient&quot;),<br>        label=&quot;inpatient&quot;,<br>    )<br>    log_sample_df(&quot;inpatient_out&quot;, inpatient)<br>    outpatient = sample_claims_from_glob(<br>        pattern=cfg[&quot;outpatient_glob&quot;],<br>        sample_size=sample_size,<br>        chunksize=chunksize,<br>        log_every_chunks=log_every_chunks,<br>        max_scan_rows=max_scan_rows_per_claim_type,<br>        rng=rng,<br>        usecols=lambda c: c in INSTITUTIONAL_COLUMNS,<br>        normalize_fn=lambda df: normalize_institutional(df, &quot;outpatient&quot;),<br>        label=&quot;outpatient&quot;,<br>    )<br>    log_sample_df(&quot;outpatient_out&quot;, outpatient)<br>    carrier = sample_claims_from_glob(<br>        pattern=cfg[&quot;carrier_glob&quot;],<br>        sample_size=sample_size,<br>        chunksize=chunksize,<br>        log_every_chunks=log_every_chunks,<br>        max_scan_rows=max_scan_rows_per_claim_type,<br>        rng=rng,<br>        usecols=carrier_usecols,<br>        normalize_fn=normalize_carrier,<br>        label=&quot;carrier&quot;,<br>    )<br>    log_sample_df(&quot;carrier_out&quot;, carrier)<br><br>    claims = pd.concat([inpatient, outpatient, carrier], ignore_index=True)<br>    claims[&quot;patient_id&quot;] = normalize_id_values(claims[&quot;patient_id&quot;])<br>    claims[&quot;provider_npi&quot;] = normalize_npi_values(claims[&quot;provider_npi&quot;])<br>    claims[&quot;facility_id&quot;] = normalize_id_values(claims[&quot;facility_id&quot;])<br><br>    needed_patient_ids = set(claims[&quot;patient_id&quot;].dropna().astype(str))<br>    bene = load_beneficiary_for_patient_ids(<br>        pattern=cfg[&quot;beneficiary_glob&quot;],<br>        patient_ids=needed_patient_ids,<br>        chunksize=chunksize,<br>        log_every_chunks=log_every_chunks,<br>    )<br>    claims = claims.merge(bene, on=&quot;patient_id&quot;, how=&quot;left&quot;)<br>    logger.info(&quot;Claims rows after merge: %d&quot;, len(claims))<br>    log_sample_df(&quot;claims_enriched&quot;, claims)<br><br>    # Add a stable synthetic billed-amount proxy because public claims here do not directly model<br>    # the exact operational charge concepts you would receive from a revenue-cycle vendor extract.<br>    charge_multiplier = rng.uniform(1.20, 2.40, size=len(claims))<br>    claims[&quot;billed_amount_proxy&quot;] = (claims[&quot;paid_amount&quot;].clip(lower=1.0) * charge_multiplier).round(2)<br><br>    needed_provider_npis = set(claims[&quot;provider_npi&quot;].dropna().astype(str))<br>    providers = load_nppes_for_provider_npis(<br>        file_path=cfg[&quot;nppes_file&quot;],<br>        provider_npis=needed_provider_npis,<br>        chunksize=chunksize,<br>        log_every_chunks=log_every_chunks,<br>        max_scan_rows=nppes_max_scan_rows,<br>    )<br><br>    facilities_all = normalize_hospital(pd.read_csv(cfg[&quot;hospital_file&quot;], low_memory=False))<br>    needed_facility_ids = set(claims[&quot;facility_id&quot;].dropna().astype(str))<br>    facilities = facilities_all[facilities_all[&quot;facility_id&quot;].isin(needed_facility_ids)].copy()<br>    if facilities.empty:<br>        logger.warning(<br>            &quot;No facility IDs from sampled claims matched hospital file; using full facility table&quot;<br>        )<br>        facilities = facilities_all<br><br>    logger.info(&quot;Providers rows: %d | Facilities rows: %d&quot;, len(providers), len(facilities))<br>    log_sample_df(&quot;providers_out&quot;, providers)<br>    log_sample_df(&quot;facilities_out&quot;, facilities)<br><br>    claims.to_csv(output_dir / &quot;claims_seed.csv&quot;, index=False)<br>    providers.to_csv(output_dir / &quot;providers_seed.csv&quot;, index=False)<br>    facilities.to_csv(output_dir / &quot;facilities_seed.csv&quot;, index=False)<br><br>    print(f&quot;Wrote seed files to {output_dir}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Vendor feed simulator: apps/simulation/build_vendor_feeds.py</li></ul><pre>import argparse<br>import logging<br>from pathlib import Path<br>from zipfile import ZipFile<br>import numpy as np<br>import pandas as pd<br><br>logger = logging.getLogger(__name__)<br><br><br>DENIAL_CODES = [<br>    (&quot;CO-16&quot;, &quot;Missing information&quot;),<br>    (&quot;CO-18&quot;, &quot;Duplicate claim&quot;),<br>    (&quot;CO-97&quot;, &quot;Bundled service&quot;),<br>    (&quot;PR-1&quot;, &quot;Deductible amount&quot;),<br>    (&quot;CO-22&quot;, &quot;Coordination of benefits&quot;),<br>    (&quot;CO-197&quot;, &quot;Precertification missing&quot;),<br>]<br><br>BOTTLENECK_STAGES = [<br>    &quot;claim_scrubbing&quot;,<br>    &quot;eligibility_followup&quot;,<br>    &quot;coding_review&quot;,<br>    &quot;authorization_followup&quot;,<br>    &quot;appeal_queue&quot;,<br>    &quot;payer_research&quot;,<br>]<br><br><br>def zip_csv(df: pd.DataFrame, zip_path: Path, csv_name: str) -&gt; None:<br>    temp_csv = zip_path.parent / csv_name<br>    df.to_csv(temp_csv, index=False)<br>    with ZipFile(zip_path, &quot;w&quot;) as zf:<br>        zf.write(temp_csv, arcname=csv_name)<br>    temp_csv.unlink(missing_ok=True)<br><br><br>def configure_logging() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br><br><br>def log_sample_df(label: str, df: pd.DataFrame, rows: int = 3) -&gt; None:<br>    logger.info(&quot;[%s] Sample rows (showing up to %d)&quot;, label, rows)<br>    if df.empty:<br>        logger.info(&quot;[%s] &lt;empty dataframe&gt;&quot;, label)<br>        return<br>    sample = df.head(rows).to_string(index=False)<br>    for line in sample.splitlines():<br>        logger.info(&quot;[%s] %s&quot;, label, line)<br><br><br>def main():<br>    configure_logging()<br><br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--seed-dir&quot;, required=True)<br>    parser.add_argument(&quot;--output-dir&quot;, required=True)<br>    parser.add_argument(&quot;--run-date&quot;, default=pd.Timestamp.utcnow().strftime(&quot;%Y-%m-%d&quot;))<br>    args = parser.parse_args()<br><br>    seed_dir = Path(args.seed_dir)<br>    output_dir = Path(args.output_dir)<br>    sftp_dir = output_dir / &quot;sftp&quot;<br>    portal_dir = output_dir / &quot;portal&quot;<br>    sftp_dir.mkdir(parents=True, exist_ok=True)<br>    portal_dir.mkdir(parents=True, exist_ok=True)<br><br>    claims = pd.read_csv(<br>        seed_dir / &quot;claims_seed.csv&quot;,<br>        parse_dates=[&quot;service_from_date&quot;, &quot;service_thru_date&quot;],<br>        low_memory=False,<br>    )<br>    providers = pd.read_csv(seed_dir / &quot;providers_seed.csv&quot;, low_memory=False)<br>    facilities = pd.read_csv(seed_dir / &quot;facilities_seed.csv&quot;, low_memory=False)<br><br>    rng = np.random.default_rng(42)<br>    run_date = pd.to_datetime(args.run_date)<br>    logger.info(<br>        &quot;Building vendor feeds | claims=%d | providers=%d | facilities=%d | run_date=%s&quot;,<br>        len(claims),<br>        len(providers),<br>        len(facilities),<br>        run_date.date(),<br>    )<br>    log_sample_df(&quot;claims_in&quot;, claims)<br>    log_sample_df(&quot;providers_in&quot;, providers)<br>    log_sample_df(&quot;facilities_in&quot;, facilities)<br><br>    facility_ids = facilities[&quot;facility_id&quot;].dropna().astype(str).tolist()<br>    if not facility_ids:<br>        raise ValueError(&quot;No facility IDs found in facilities_seed.csv&quot;)<br><br>    # Fill missing facility IDs for carrier claims by assigning same-state or random facility.<br>    mask_missing_facility = claims[&quot;facility_id&quot;].isna() | (claims[&quot;facility_id&quot;].astype(str).isin([&quot;None&quot;, &quot;nan&quot;]))<br>    claims.loc[mask_missing_facility, &quot;facility_id&quot;] = rng.choice(facility_ids, size=mask_missing_facility.sum())<br><br>    claims[&quot;claim_received_at&quot;] = claims[&quot;service_thru_date&quot;] + pd.to_timedelta(rng.integers(1, 8, size=len(claims)), unit=&quot;D&quot;)<br>    claims[&quot;expected_allowed_amount&quot;] = (claims[&quot;billed_amount_proxy&quot;] * rng.uniform(0.55, 0.90, size=len(claims))).round(2)<br><br>    denial_draw = rng.random(len(claims))<br>    denial_flag = denial_draw &lt; np.where(claims[&quot;claim_type&quot;].eq(&quot;carrier&quot;), 0.16, 0.10)<br><br>    denial_reason_code = []<br>    denial_reason_text = []<br>    remit_status = []<br>    adjudicated_at = []<br>    paid_amount = []<br><br>    progress_every = 25000<br>    for i, row in enumerate(claims.itertuples(index=False), start=0):<br>        if i == 0 or (i + 1) % progress_every == 0:<br>            logger.info(&quot;Processing remittance simulation row %d/%d&quot;, i + 1, len(claims))<br>        lag_days = int(rng.integers(3, 45))<br>        adjudicated_at.append(row.claim_received_at + pd.to_timedelta(lag_days, unit=&quot;D&quot;))<br>        if denial_flag[i]:<br>            code, text = DENIAL_CODES[int(rng.integers(0, len(DENIAL_CODES)))]<br>            denial_reason_code.append(code)<br>            denial_reason_text.append(text)<br>            status_choice = &quot;DENIED&quot; if rng.random() &lt; 0.75 else &quot;PARTIAL&quot;<br>            remit_status.append(status_choice)<br>            if status_choice == &quot;DENIED&quot;:<br>                paid_amount.append(0.0)<br>            else:<br>                paid_amount.append(round(float(row.expected_allowed_amount) * rng.uniform(0.20, 0.60), 2))<br>        else:<br>            denial_reason_code.append(None)<br>            denial_reason_text.append(None)<br>            remit_status.append(&quot;PAID&quot;)<br>            paid_amount.append(round(float(row.expected_allowed_amount) * rng.uniform(0.85, 1.00), 2))<br><br>    claims_out = claims.copy()<br>    claims_out[&quot;source_system&quot;] = &quot;vendor_sftp&quot;<br>    claims_out[&quot;payer_name&quot;] = rng.choice([&quot;Medicare FFS&quot;, &quot;Commercial PPO&quot;, &quot;Medicaid MCO&quot;], size=len(claims_out), p=[0.55, 0.30, 0.15])<br>    claims_out[&quot;billed_amount&quot;] = claims_out[&quot;billed_amount_proxy&quot;].round(2)<br>    claims_out[&quot;load_run_date&quot;] = run_date.date()<br><br>    claims_out = claims_out[<br>        [<br>            &quot;claim_id&quot;,<br>            &quot;patient_id&quot;,<br>            &quot;claim_type&quot;,<br>            &quot;facility_id&quot;,<br>            &quot;provider_npi&quot;,<br>            &quot;service_from_date&quot;,<br>            &quot;service_thru_date&quot;,<br>            &quot;claim_received_at&quot;,<br>            &quot;billed_amount&quot;,<br>            &quot;expected_allowed_amount&quot;,<br>            &quot;payer_name&quot;,<br>            &quot;procedure_code&quot;,<br>            &quot;patient_state&quot;,<br>            &quot;source_system&quot;,<br>            &quot;load_run_date&quot;,<br>        ]<br>    ]<br><br>    remits = pd.DataFrame(<br>        {<br>            &quot;remittance_id&quot;: [f&quot;RMT-{i:09d}&quot; for i in range(1, len(claims_out) + 1)],<br>            &quot;claim_id&quot;: claims_out[&quot;claim_id&quot;],<br>            &quot;adjudicated_at&quot;: adjudicated_at,<br>            &quot;remit_status&quot;: remit_status,<br>            &quot;paid_amount&quot;: paid_amount,<br>            &quot;patient_responsibility&quot;: np.round(np.array(claims_out[&quot;expected_allowed_amount&quot;]) * rng.uniform(0.05, 0.20, size=len(claims_out)), 2),<br>            &quot;adjustment_amount&quot;: np.round(np.array(claims_out[&quot;billed_amount&quot;]) - np.array(paid_amount), 2),<br>            &quot;denial_reason_code&quot;: denial_reason_code,<br>            &quot;denial_reason_text&quot;: denial_reason_text,<br>            &quot;source_system&quot;: &quot;vendor_sftp&quot;,<br>            &quot;load_run_date&quot;: run_date.date(),<br>        }<br>    )<br><br>    workqueue = pd.DataFrame(<br>        {<br>            &quot;claim_id&quot;: claims_out[&quot;claim_id&quot;],<br>            &quot;queue_name&quot;: rng.choice([&quot;front_end&quot;, &quot;mid_cycle&quot;, &quot;denials&quot;, &quot;appeals&quot;], size=len(claims_out)),<br>            &quot;current_owner&quot;: rng.choice([&quot;team_alpha&quot;, &quot;team_beta&quot;, &quot;team_gamma&quot;], size=len(claims_out)),<br>            &quot;aging_bucket&quot;: pd.cut(<br>                (pd.to_datetime(adjudicated_at) - pd.to_datetime(claims_out[&quot;claim_received_at&quot;])).dt.days,<br>                bins=[-1, 7, 15, 30, 9999],<br>                labels=[&quot;0-7&quot;, &quot;8-15&quot;, &quot;16-30&quot;, &quot;31+&quot;],<br>            ).astype(str),<br>            &quot;bottleneck_stage&quot;: rng.choice(BOTTLENECK_STAGES, size=len(claims_out)),<br>            &quot;denial_reason_code&quot;: denial_reason_code,<br>            &quot;touch_count&quot;: rng.integers(1, 6, size=len(claims_out)),<br>            &quot;reopened_flag&quot;: rng.choice([0, 1], size=len(claims_out), p=[0.85, 0.15]),<br>            &quot;last_touched_at&quot;: pd.to_datetime(adjudicated_at) - pd.to_timedelta(rng.integers(0, 5, size=len(claims_out)), unit=&quot;D&quot;),<br>            &quot;source_system&quot;: &quot;vendor_portal&quot;,<br>            &quot;load_run_date&quot;: run_date.date(),<br>        }<br>    )<br><br>    patient_access = pd.DataFrame(<br>        {<br>            &quot;facility_id&quot;: facilities[&quot;facility_id&quot;].astype(str),<br>            &quot;event_date&quot;: run_date.date(),<br>            &quot;referred_patients&quot;: rng.integers(25, 250, size=len(facilities)),<br>            &quot;scheduled_patients&quot;: rng.integers(20, 220, size=len(facilities)),<br>            &quot;completed_first_visit&quot;: rng.integers(15, 200, size=len(facilities)),<br>            &quot;avg_days_to_appointment&quot;: np.round(rng.uniform(2.0, 18.0, size=len(facilities)), 1),<br>            &quot;source_system&quot;: &quot;vendor_portal&quot;,<br>            &quot;load_run_date&quot;: run_date.date(),<br>        }<br>    )<br>    patient_access[&quot;scheduled_patients&quot;] = patient_access[[&quot;referred_patients&quot;, &quot;scheduled_patients&quot;]].min(axis=1)<br>    patient_access[&quot;completed_first_visit&quot;] = patient_access[[&quot;scheduled_patients&quot;, &quot;completed_first_visit&quot;]].min(axis=1)<br><br>    claims_out.to_csv(sftp_dir / f&quot;vendor_claims_{run_date.date()}.csv&quot;, index=False)<br>    remits.to_csv(sftp_dir / f&quot;vendor_remits_{run_date.date()}.csv&quot;, index=False)<br>    providers.to_csv(sftp_dir / f&quot;provider_reference_{run_date.date()}.csv&quot;, index=False)<br>    facilities.to_csv(sftp_dir / f&quot;facility_reference_{run_date.date()}.csv&quot;, index=False)<br><br>    zip_csv(workqueue, portal_dir / f&quot;workqueue_{run_date.date()}.zip&quot;, f&quot;workqueue_{run_date.date()}.csv&quot;)<br>    zip_csv(patient_access, portal_dir / f&quot;patient_access_{run_date.date()}.zip&quot;, f&quot;patient_access_{run_date.date()}.csv&quot;)<br><br>    log_sample_df(&quot;claims_out&quot;, claims_out)<br>    log_sample_df(&quot;remits_out&quot;, remits)<br>    log_sample_df(&quot;workqueue_out&quot;, workqueue)<br>    log_sample_df(&quot;patient_access_out&quot;, patient_access)<br><br>    logger.info(&quot;Feed generation complete | output_dir=%s&quot;, output_dir)<br>    print(f&quot;Generated vendor feeds in {output_dir}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Bronze ingestion: apps/ingestion/local_bronze_ingest.py</li></ul><pre>import argparse<br>import hashlib<br>import json<br>import os<br>import re<br>import tempfile<br>from datetime import datetime, timezone<br>from pathlib import Path<br>from zipfile import ZipFile<br><br>import boto3<br>from dotenv import load_dotenv<br><br><br>load_dotenv()<br><br>RUN_DATE_RE = re.compile(r&quot;(\d{4}-\d{2}-\d{2})&quot;)<br>SFTP_FEED_PREFIXES = {<br>    &quot;vendor_claims_&quot;: &quot;vendor_claims&quot;,<br>    &quot;vendor_remits_&quot;: &quot;vendor_remits&quot;,<br>    &quot;provider_reference_&quot;: &quot;provider_reference&quot;,<br>    &quot;facility_reference_&quot;: &quot;facility_reference&quot;,<br>}<br>PORTAL_FEED_PREFIXES = {<br>    &quot;workqueue_&quot;: &quot;workqueue&quot;,<br>    &quot;patient_access_&quot;: &quot;patient_access&quot;,<br>}<br><br><br>def s3_client():<br>    return boto3.client(&quot;s3&quot;, region_name=os.getenv(&quot;AWS_REGION&quot;, &quot;us-east-1&quot;))<br><br><br>def parse_args() -&gt; argparse.Namespace:<br>    parser = argparse.ArgumentParser(<br>        description=&quot;Upload local vendor feed files into Bronze S3 prefixes with idempotent control manifests.&quot;<br>    )<br>    parser.add_argument(&quot;--data-bucket&quot;, required=True)<br>    parser.add_argument(&quot;--feeds-dir&quot;, default=&quot;./data/vendor_feeds&quot;)<br>    parser.add_argument(&quot;--run-date&quot;, default=&quot;&quot;)<br>    parser.add_argument(&quot;--sample-rows&quot;, type=int, default=3)<br>    parser.add_argument(&quot;--chunk-size-mb&quot;, type=int, default=8)<br>    return parser.parse_args()<br><br><br>def object_exists(client, bucket: str, key: str) -&gt; bool:<br>    try:<br>        client.head_object(Bucket=bucket, Key=key)<br>        return True<br>    except Exception:<br>        return False<br><br><br>def infer_feed_type(filename: str, source: str) -&gt; str | None:<br>    lowered = filename.lower()<br>    prefixes = SFTP_FEED_PREFIXES if source == &quot;sftp&quot; else PORTAL_FEED_PREFIXES<br>    for prefix, feed_type in prefixes.items():<br>        if lowered.startswith(prefix):<br>            return feed_type<br>    return None<br><br><br>def infer_ingest_date(filename: str, fallback_date: str) -&gt; str:<br>    match = RUN_DATE_RE.search(filename)<br>    if match:<br>        return match.group(1)<br>    return fallback_date<br><br><br>def file_md5(path: Path, chunk_size: int) -&gt; str:<br>    digest = hashlib.md5()<br>    with path.open(&quot;rb&quot;) as handle:<br>        while True:<br>            chunk = handle.read(chunk_size)<br>            if not chunk:<br>                break<br>            digest.update(chunk)<br>    return digest.hexdigest()<br><br><br>def print_csv_sample(path: Path, label: str, sample_rows: int) -&gt; None:<br>    print(f&quot;[sample] {label}: {path}&quot;)<br>    printed = 0<br>    with path.open(&quot;r&quot;, encoding=&quot;utf-8&quot;, errors=&quot;replace&quot;) as handle:<br>        for line in handle:<br>            print(f&quot;[sample] {line.rstrip()}&quot;)<br>            printed += 1<br>            if printed &gt;= sample_rows + 1:<br>                break<br>    if printed == 0:<br>        print(&quot;[sample] &lt;empty file&gt;&quot;)<br><br><br>def upload_file_to_bronze(<br>    s3,<br>    bucket: str,<br>    source: str,<br>    feed_type: str,<br>    local_path: Path,<br>    ingest_date: str,<br>    chunk_size: int,<br>) -&gt; tuple[bool, str]:<br>    md5 = file_md5(local_path, chunk_size)<br>    state_key = f&quot;control/source={source}/md5={md5}.json&quot;<br>    if object_exists(s3, bucket, state_key):<br>        return False, &quot;&quot;<br><br>    bronze_key = (<br>        f&quot;bronze/source={source}/feed={feed_type}/&quot;<br>        f&quot;ingest_date={ingest_date}/{local_path.name}&quot;<br>    )<br><br>    s3.upload_file(<br>        str(local_path),<br>        bucket,<br>        bronze_key,<br>        ExtraArgs={&quot;Metadata&quot;: {&quot;md5&quot;: md5, &quot;source&quot;: source, &quot;feed_type&quot;: feed_type}},<br>    )<br><br>    manifest = {<br>        &quot;source&quot;: source,<br>        &quot;feed_type&quot;: feed_type,<br>        &quot;filename&quot;: local_path.name,<br>        &quot;bronze_key&quot;: bronze_key,<br>        &quot;md5&quot;: md5,<br>        &quot;ingested_at_utc&quot;: datetime.now(timezone.utc).isoformat(),<br>    }<br>    s3.put_object(Bucket=bucket, Key=state_key, Body=json.dumps(manifest).encode(&quot;utf-8&quot;))<br>    return True, bronze_key<br><br><br>def run() -&gt; None:<br>    args = parse_args()<br>    feeds_dir = Path(args.feeds_dir)<br>    if not feeds_dir.exists():<br>        raise FileNotFoundError(f&quot;Feeds directory does not exist: {feeds_dir}&quot;)<br><br>    if args.sample_rows &lt;= 0:<br>        raise ValueError(&quot;--sample-rows must be &gt; 0&quot;)<br><br>    chunk_size = args.chunk_size_mb * 1024 * 1024<br>    if chunk_size &lt;= 0:<br>        raise ValueError(&quot;--chunk-size-mb must be &gt; 0&quot;)<br><br>    run_date_filter = args.run_date.strip()<br>    fallback_date = run_date_filter or datetime.now(timezone.utc).date().isoformat()<br><br>    s3 = s3_client()<br>    processed = 0<br>    skipped = 0<br><br>    sftp_files = sorted((feeds_dir / &quot;sftp&quot;).glob(&quot;*.csv&quot;))<br>    portal_files = sorted((feeds_dir / &quot;portal&quot;).glob(&quot;*.zip&quot;))<br><br>    if run_date_filter:<br>        sftp_files = [p for p in sftp_files if run_date_filter in p.name]<br>        portal_files = [p for p in portal_files if run_date_filter in p.name]<br><br>    print(<br>        f&quot;[info] Found files | sftp_csv={len(sftp_files)} | portal_zip={len(portal_files)}&quot;<br>    )<br><br>    total_steps = len(sftp_files) + len(portal_files)<br>    step = 0<br><br>    for path in sftp_files:<br>        step += 1<br>        feed_type = infer_feed_type(path.name, &quot;sftp&quot;)<br>        if not feed_type:<br>            print(f&quot;[warn] Skipping unknown sftp feed file: {path.name}&quot;)<br>            continue<br><br>        ingest_date = infer_ingest_date(path.name, fallback_date)<br>        print(f&quot;[ingest] {step}/{total_steps} sftp {path.name} -&gt; feed={feed_type} ingest_date={ingest_date}&quot;)<br>        print_csv_sample(path, &quot;incoming&quot;, args.sample_rows)<br><br>        uploaded, bronze_key = upload_file_to_bronze(<br>            s3=s3,<br>            bucket=args.data_bucket,<br>            source=&quot;sftp&quot;,<br>            feed_type=feed_type,<br>            local_path=path,<br>            ingest_date=ingest_date,<br>            chunk_size=chunk_size,<br>        )<br>        if uploaded:<br>            processed += 1<br>            print(f&quot;[sample] outgoing_s3_key={bronze_key}&quot;)<br>        else:<br>            skipped += 1<br>            print(f&quot;[skip] Duplicate payload already ingested: {path.name}&quot;)<br><br>    for path in portal_files:<br>        step += 1<br>        print(f&quot;[ingest] {step}/{total_steps} portal {path.name}&quot;)<br>        with tempfile.TemporaryDirectory() as tmpdir:<br>            tmpdir_path = Path(tmpdir)<br>            with ZipFile(path, &quot;r&quot;) as zf:<br>                members = [<br>                    m for m in zf.namelist()<br>                    if m.lower().endswith(&quot;.csv&quot;) and not m.endswith(&quot;/&quot;)<br>                ]<br>                if not members:<br>                    print(f&quot;[warn] No CSV members found in {path.name}&quot;)<br>                    continue<br><br>                for member in members:<br>                    member_name = Path(member).name<br>                    feed_type = infer_feed_type(member_name, &quot;portal&quot;)<br>                    if not feed_type:<br>                        print(f&quot;[warn] Skipping unknown portal feed member: {member_name}&quot;)<br>                        continue<br><br>                    ingest_date = infer_ingest_date(member_name, fallback_date)<br>                    local_csv = tmpdir_path / member_name<br>                    with zf.open(member, &quot;r&quot;) as src, local_csv.open(&quot;wb&quot;) as dst:<br>                        while True:<br>                            chunk = src.read(chunk_size)<br>                            if not chunk:<br>                                break<br>                            dst.write(chunk)<br><br>                    print(<br>                        f&quot;[ingest] portal member {member_name} -&gt; feed={feed_type} ingest_date={ingest_date}&quot;<br>                    )<br>                    print_csv_sample(local_csv, &quot;incoming&quot;, args.sample_rows)<br><br>                    uploaded, bronze_key = upload_file_to_bronze(<br>                        s3=s3,<br>                        bucket=args.data_bucket,<br>                        source=&quot;portal&quot;,<br>                        feed_type=feed_type,<br>                        local_path=local_csv,<br>                        ingest_date=ingest_date,<br>                        chunk_size=chunk_size,<br>                    )<br>                    if uploaded:<br>                        processed += 1<br>                        print(f&quot;[sample] outgoing_s3_key={bronze_key}&quot;)<br>                    else:<br>                        skipped += 1<br>                        print(<br>                            f&quot;[skip] Duplicate payload already ingested: {path.name}:{member_name}&quot;<br>                        )<br><br>    print(json.dumps({&quot;processed&quot;: processed, &quot;skipped&quot;: skipped}, indent=2))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    run()</pre><ul><li>Bronze to Silver: spark/bronze_to_silver.py</li></ul><pre># NOTE:<br># This job currently scans all historical bronze partitions (wildcard ingest_date paths),<br># then performs wide dedupe/merge operations. It is fine for demo volume, but as data grows<br># it can become slow and memory-heavy. Prefer incremental partition reads for production scale.<br>import argparse<br>import logging<br>from datetime import datetime, timezone<br><br>import yaml<br>from pyspark.sql import SparkSession, functions as F, types as T<br><br>logger = logging.getLogger(__name__)<br><br>try:<br>    import boto3<br>    from botocore.exceptions import ClientError<br>except Exception:  # pragma: no cover - fallback for slim Spark image without boto3<br>    boto3 = None<br>    ClientError = Exception<br><br><br>def build_spark(app_name: str, warehouse: str) -&gt; SparkSession:<br>    return (<br>        SparkSession.builder.appName(app_name)<br>        .config(&quot;spark.sql.catalog.glue_catalog&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.warehouse&quot;, warehouse)<br>        .config(&quot;spark.sql.catalog.glue_catalog.catalog-impl&quot;, &quot;org.apache.iceberg.aws.glue.GlueCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.io-impl&quot;, &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.cache-enabled&quot;, &quot;false&quot;)<br>        .config(&quot;spark.sql.extensions&quot;, &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)<br>        .config(&quot;spark.sql.adaptive.enabled&quot;, &quot;true&quot;)<br>        .config(&quot;spark.sql.shuffle.partitions&quot;, &quot;64&quot;)<br>        .getOrCreate()<br>    )<br><br><br>def required_columns(df, required):<br>    missing = [c for c in required if c not in df.columns]<br>    if missing:<br>        raise ValueError(f&quot;Missing required columns: {missing}&quot;)<br><br><br>def create_databases(spark):<br>    spark.sql(&quot;CREATE DATABASE IF NOT EXISTS glue_catalog.hc_rcm_silver&quot;)<br>    spark.sql(&quot;CREATE DATABASE IF NOT EXISTS glue_catalog.hc_rcm_gold&quot;)<br><br><br>def read_contracts(path: str):<br>    with open(path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        return yaml.safe_load(f)<br><br><br>def configure_logging() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br><br><br>def log_df_sample(label: str, df, rows: int) -&gt; None:<br>    logger.info(&quot;[%s] columns=%s&quot;, label, &quot;, &quot;.join(df.columns))<br>    for row in df.limit(rows).toJSON().collect():<br>        logger.info(&quot;[%s] %s&quot;, label, row)<br><br><br>def standardize_claims(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;claim_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;patient_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;claim_type&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;facility_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;provider_npi&quot;).cast(&quot;string&quot;),<br>            F.to_date(&quot;service_from_date&quot;).alias(&quot;service_from_date&quot;),<br>            F.to_date(&quot;service_thru_date&quot;).alias(&quot;service_thru_date&quot;),<br>            F.to_timestamp(&quot;claim_received_at&quot;).alias(&quot;claim_received_at&quot;),<br>            F.col(&quot;billed_amount&quot;).cast(T.DecimalType(18, 2)),<br>            F.col(&quot;expected_allowed_amount&quot;).cast(T.DecimalType(18, 2)),<br>            F.col(&quot;payer_name&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;procedure_code&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;patient_state&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;source_system&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;load_run_date&quot;).cast(&quot;date&quot;).alias(&quot;load_run_date&quot;),<br>            F.col(&quot;_metadata.file_path&quot;).cast(&quot;string&quot;).alias(&quot;src_file_name&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .withColumn(&quot;service_month&quot;, F.date_trunc(&quot;month&quot;, F.col(&quot;service_from_date&quot;)))<br>        .dropDuplicates([&quot;claim_id&quot;])<br>    )<br><br><br>def standardize_remits(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;remittance_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;claim_id&quot;).cast(&quot;string&quot;),<br>            F.to_timestamp(&quot;adjudicated_at&quot;).alias(&quot;adjudicated_at&quot;),<br>            F.col(&quot;remit_status&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;paid_amount&quot;).cast(T.DecimalType(18, 2)),<br>            F.col(&quot;patient_responsibility&quot;).cast(T.DecimalType(18, 2)),<br>            F.col(&quot;adjustment_amount&quot;).cast(T.DecimalType(18, 2)),<br>            F.col(&quot;denial_reason_code&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;denial_reason_text&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;source_system&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;load_run_date&quot;).cast(&quot;date&quot;).alias(&quot;load_run_date&quot;),<br>            F.col(&quot;_metadata.file_path&quot;).cast(&quot;string&quot;).alias(&quot;src_file_name&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .withColumn(&quot;adjudication_month&quot;, F.date_trunc(&quot;month&quot;, F.col(&quot;adjudicated_at&quot;)))<br>        .dropDuplicates([&quot;remittance_id&quot;])<br>    )<br><br><br>def standardize_workqueue(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;claim_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;queue_name&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;current_owner&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;aging_bucket&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;bottleneck_stage&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;denial_reason_code&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;touch_count&quot;).cast(&quot;int&quot;),<br>            F.col(&quot;reopened_flag&quot;).cast(&quot;int&quot;),<br>            F.to_timestamp(&quot;last_touched_at&quot;).alias(&quot;last_touched_at&quot;),<br>            F.col(&quot;source_system&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;load_run_date&quot;).cast(&quot;date&quot;).alias(&quot;load_run_date&quot;),<br>            F.col(&quot;_metadata.file_path&quot;).cast(&quot;string&quot;).alias(&quot;src_file_name&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .dropDuplicates([&quot;claim_id&quot;, &quot;load_run_date&quot;])<br>    )<br><br><br>def standardize_patient_access(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;facility_id&quot;).cast(&quot;string&quot;),<br>            F.to_date(&quot;event_date&quot;).alias(&quot;event_date&quot;),<br>            F.col(&quot;referred_patients&quot;).cast(&quot;int&quot;),<br>            F.col(&quot;scheduled_patients&quot;).cast(&quot;int&quot;),<br>            F.col(&quot;completed_first_visit&quot;).cast(&quot;int&quot;),<br>            F.col(&quot;avg_days_to_appointment&quot;).cast(T.DecimalType(10, 1)),<br>            F.col(&quot;source_system&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;load_run_date&quot;).cast(&quot;date&quot;).alias(&quot;load_run_date&quot;),<br>            F.col(&quot;_metadata.file_path&quot;).cast(&quot;string&quot;).alias(&quot;src_file_name&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .dropDuplicates([&quot;facility_id&quot;, &quot;event_date&quot;])<br>    )<br><br><br>def standardize_providers(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;provider_npi&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;provider_name&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;taxonomy_code&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;is_primary_taxonomy&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;city&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;state&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;zip_code&quot;).cast(&quot;string&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .dropDuplicates([&quot;provider_npi&quot;])<br>    )<br><br><br>def standardize_facilities(df, ingest_ts):<br>    return (<br>        df.select(<br>            F.col(&quot;facility_id&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;facility_name&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;state&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;city&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;zip_code&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;hospital_type&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;ownership&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;overall_rating&quot;).cast(&quot;string&quot;),<br>            F.col(&quot;emergency_services&quot;).cast(&quot;string&quot;),<br>            F.lit(ingest_ts).cast(&quot;timestamp&quot;).alias(&quot;ingested_at_utc&quot;),<br>        )<br>        .dropDuplicates([&quot;facility_id&quot;])<br>    )<br><br><br>def merge_table(spark, df, target_table, keys):<br>    temp_view = f&quot;tmp_{target_table.split(&#39;.&#39;)[-1]}&quot;<br>    df.createOrReplaceTempView(temp_view)<br>    on_clause = &quot; AND &quot;.join([f&quot;t.{k} = s.{k}&quot; for k in keys])<br>    update_clause = &quot;, &quot;.join([f&quot;t.{c} = s.{c}&quot; for c in df.columns if c not in keys])<br>    insert_cols = &quot;, &quot;.join(df.columns)<br>    insert_vals = &quot;, &quot;.join([f&quot;s.{c}&quot; for c in df.columns])<br><br>    spark.sql(<br>        f&quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS {target_table}<br>        USING iceberg<br>        AS SELECT * FROM {temp_view} WHERE 1=0<br>        &quot;&quot;&quot;<br>    )<br>    spark.sql(<br>        f&quot;&quot;&quot;<br>        MERGE INTO {target_table} t<br>        USING {temp_view} s<br>        ON {on_clause}<br>        WHEN MATCHED THEN UPDATE SET {update_clause}<br>        WHEN NOT MATCHED THEN INSERT ({insert_cols}) VALUES ({insert_vals})<br>        &quot;&quot;&quot;<br>    )<br><br><br>def replace_table(spark, df, target_table):<br>    temp_view = f&quot;tmp_{target_table.split(&#39;.&#39;)[-1]}&quot;<br>    df.createOrReplaceTempView(temp_view)<br>    sql = f&quot;&quot;&quot;<br>        CREATE OR REPLACE TABLE {target_table}<br>        USING iceberg<br>        AS SELECT * FROM {temp_view}<br>        &quot;&quot;&quot;<br><br>    def force_delete_glue_table() -&gt; None:<br>        parts = target_table.split(&quot;.&quot;)<br>        if len(parts) != 3:<br>            raise ValueError(f&quot;Expected catalog.database.table, got: {target_table}&quot;)<br>        database, table_name = parts[1], parts[2]<br>        if boto3 is not None:<br>            glue = boto3.client(&quot;glue&quot;)<br>            try:<br>                glue.delete_table(DatabaseName=database, Name=table_name)<br>                logger.warning(<br>                    &quot;Deleted stale Glue table metadata for %s.%s via boto3&quot;,<br>                    database,<br>                    table_name,<br>                )<br>                return<br>            except ClientError as delete_err:<br>                code = delete_err.response.get(&quot;Error&quot;, {}).get(&quot;Code&quot;)<br>                if code == &quot;EntityNotFoundException&quot;:<br>                    return<br>                raise<br><br>        # Fallback path when boto3 is not available in the Spark runtime image.<br>        jvm = spark._jvm<br>        glue_client = jvm.software.amazon.awssdk.services.glue.GlueClient.builder().build()<br>        try:<br>            request = (<br>                jvm.software.amazon.awssdk.services.glue.model.DeleteTableRequest.builder()<br>                .databaseName(database)<br>                .name(table_name)<br>                .build()<br>            )<br>            glue_client.deleteTable(request)<br>            logger.warning(<br>                &quot;Deleted stale Glue table metadata for %s.%s via AWS SDK&quot;,<br>                database,<br>                table_name,<br>            )<br>        except Exception as delete_err:  # py4j wraps Java exceptions<br>            if &quot;EntityNotFoundException&quot; in str(delete_err):<br>                return<br>            raise<br>        finally:<br>            glue_client.close()<br><br>    try:<br>        spark.sql(sql)<br>    except Exception as exc:<br>        message = str(exc)<br>        # Self-heal when Glue points to a missing Iceberg metadata.json in S3.<br>        if &quot;Location does not exist&quot; in message or &quot;NoSuchKeyException&quot; in message:<br>            logger.warning(<br>                &quot;Detected stale Iceberg metadata for %s; deleting Glue table and retrying replace&quot;,<br>                target_table,<br>            )<br>            force_delete_glue_table()<br>            spark.sql(sql)<br>            return<br>        raise<br><br><br>def write_table(spark, df, target_table, keys, mode):<br>    if mode == &quot;replace&quot;:<br>        replace_table(spark, df, target_table)<br>        return<br>    merge_table(spark, df, target_table, keys)<br><br><br>def main():<br>    configure_logging()<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--warehouse&quot;, required=True)<br>    parser.add_argument(&quot;--data-bucket&quot;, required=True)<br>    parser.add_argument(&quot;--contracts&quot;, required=True)<br>    parser.add_argument(&quot;--write-mode&quot;, choices=[&quot;merge&quot;, &quot;replace&quot;], default=&quot;merge&quot;)<br>    parser.add_argument(&quot;--sample-rows&quot;, type=int, default=3)<br>    args = parser.parse_args()<br><br>    spark = build_spark(&quot;hc-rcm-bronze-to-silver&quot;, args.warehouse)<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br>    contracts = read_contracts(args.contracts)<br>    create_databases(spark)<br>    ingest_ts = datetime.now(timezone.utc)<br><br>    base = f&quot;s3://{args.data_bucket}/bronze&quot;<br><br>    claims_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=sftp/feed=vendor_claims/*/*.csv&quot;)<br>    remits_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=sftp/feed=vendor_remits/*/*.csv&quot;)<br>    providers_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=sftp/feed=provider_reference/*/*.csv&quot;)<br>    facilities_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=sftp/feed=facility_reference/*/*.csv&quot;)<br>    workqueue_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=portal/feed=workqueue/*/*.csv&quot;)<br>    patient_access_raw = spark.read.option(&quot;header&quot;, True).csv(f&quot;{base}/source=portal/feed=patient_access/*/*.csv&quot;)<br>    log_df_sample(&quot;claims_raw_in&quot;, claims_raw, args.sample_rows)<br>    log_df_sample(&quot;remits_raw_in&quot;, remits_raw, args.sample_rows)<br>    log_df_sample(&quot;providers_raw_in&quot;, providers_raw, args.sample_rows)<br>    log_df_sample(&quot;facilities_raw_in&quot;, facilities_raw, args.sample_rows)<br>    log_df_sample(&quot;workqueue_raw_in&quot;, workqueue_raw, args.sample_rows)<br>    log_df_sample(&quot;patient_access_raw_in&quot;, patient_access_raw, args.sample_rows)<br><br>    required_columns(claims_raw, contracts[&quot;raw_claims&quot;][&quot;required_columns&quot;])<br>    required_columns(remits_raw, contracts[&quot;raw_remits&quot;][&quot;required_columns&quot;])<br>    required_columns(workqueue_raw, contracts[&quot;raw_workqueue&quot;][&quot;required_columns&quot;])<br>    required_columns(patient_access_raw, contracts[&quot;raw_patient_access&quot;][&quot;required_columns&quot;])<br><br>    claims = standardize_claims(claims_raw, ingest_ts)<br>    remits = standardize_remits(remits_raw, ingest_ts)<br>    workqueue = standardize_workqueue(workqueue_raw, ingest_ts)<br>    patient_access = standardize_patient_access(patient_access_raw, ingest_ts)<br>    providers = standardize_providers(providers_raw, ingest_ts)<br>    facilities = standardize_facilities(facilities_raw, ingest_ts)<br><br>    denial_events = (<br>        remits.filter(F.col(&quot;denial_reason_code&quot;).isNotNull())<br>        .select(<br>            &quot;claim_id&quot;,<br>            &quot;adjudicated_at&quot;,<br>            &quot;adjudication_month&quot;,<br>            &quot;denial_reason_code&quot;,<br>            &quot;denial_reason_text&quot;,<br>            &quot;remit_status&quot;,<br>            &quot;src_file_name&quot;,<br>            &quot;ingested_at_utc&quot;,<br>        )<br>        .dropDuplicates([&quot;claim_id&quot;, &quot;denial_reason_code&quot;, &quot;adjudicated_at&quot;])<br>    )<br><br>    write_table(spark, providers, &quot;glue_catalog.hc_rcm_silver.providers&quot;, [&quot;provider_npi&quot;], args.write_mode)<br>    write_table(spark, facilities, &quot;glue_catalog.hc_rcm_silver.facilities&quot;, [&quot;facility_id&quot;], args.write_mode)<br>    write_table(spark, claims, &quot;glue_catalog.hc_rcm_silver.claims&quot;, [&quot;claim_id&quot;], args.write_mode)<br>    write_table(spark, remits, &quot;glue_catalog.hc_rcm_silver.remits&quot;, [&quot;remittance_id&quot;], args.write_mode)<br>    write_table(spark, workqueue, &quot;glue_catalog.hc_rcm_silver.workqueue&quot;, [&quot;claim_id&quot;, &quot;load_run_date&quot;], args.write_mode)<br>    write_table(spark, patient_access, &quot;glue_catalog.hc_rcm_silver.patient_access&quot;, [&quot;facility_id&quot;, &quot;event_date&quot;], args.write_mode)<br>    write_table(spark, denial_events, &quot;glue_catalog.hc_rcm_silver.denial_events&quot;, [&quot;claim_id&quot;, &quot;denial_reason_code&quot;, &quot;adjudicated_at&quot;], args.write_mode)<br>    log_df_sample(&quot;claims_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.claims&quot;), args.sample_rows)<br>    log_df_sample(&quot;remits_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.remits&quot;), args.sample_rows)<br>    log_df_sample(&quot;providers_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.providers&quot;), args.sample_rows)<br>    log_df_sample(&quot;facilities_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.facilities&quot;), args.sample_rows)<br>    log_df_sample(&quot;workqueue_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.workqueue&quot;), args.sample_rows)<br>    log_df_sample(&quot;patient_access_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.patient_access&quot;), args.sample_rows)<br>    log_df_sample(&quot;denial_events_silver_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_silver.denial_events&quot;), args.sample_rows)<br><br>    # Apply table properties and partitioning where needed<br>    spark.sql(&quot;&quot;&quot;<br>        ALTER TABLE glue_catalog.hc_rcm_silver.claims<br>        SET TBLPROPERTIES (<br>          &#39;format-version&#39;=&#39;2&#39;,<br>          &#39;write.target-file-size-bytes&#39;=&#39;134217728&#39;<br>        )<br>    &quot;&quot;&quot;)<br>    spark.sql(&quot;&quot;&quot;<br>        ALTER TABLE glue_catalog.hc_rcm_silver.remits<br>        SET TBLPROPERTIES (<br>          &#39;format-version&#39;=&#39;2&#39;,<br>          &#39;write.target-file-size-bytes&#39;=&#39;134217728&#39;<br>        )<br>    &quot;&quot;&quot;)<br><br>    spark.stop()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Silver to Gold + S3 export: spark/silver_to_gold.py</li></ul><pre>import argparse<br>import logging<br>import shutil<br>import tempfile<br>from pathlib import Path<br><br>from pyspark.sql import SparkSession, functions as F<br><br>logger = logging.getLogger(__name__)<br><br>try:<br>    import boto3<br>    from botocore.exceptions import ClientError<br>except Exception:  # pragma: no cover - fallback for slim Spark image without boto3<br>    boto3 = None<br>    ClientError = Exception<br><br><br>def build_spark(app_name: str, warehouse: str) -&gt; SparkSession:<br>    return (<br>        SparkSession.builder.appName(app_name)<br>        .config(&quot;spark.sql.catalog.glue_catalog&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.warehouse&quot;, warehouse)<br>        .config(&quot;spark.sql.catalog.glue_catalog.catalog-impl&quot;, &quot;org.apache.iceberg.aws.glue.GlueCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.io-impl&quot;, &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.cache-enabled&quot;, &quot;false&quot;)<br>        .config(&quot;spark.sql.extensions&quot;, &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)<br>        .config(&quot;spark.sql.adaptive.enabled&quot;, &quot;true&quot;)<br>        .config(&quot;spark.sql.shuffle.partitions&quot;, &quot;64&quot;)<br>        .getOrCreate()<br>    )<br><br><br>def merge_table(spark, df, target_table, keys):<br>    temp_view = f&quot;tmp_{target_table.split(&#39;.&#39;)[-1]}&quot;<br>    df.createOrReplaceTempView(temp_view)<br>    on_clause = &quot; AND &quot;.join([f&quot;t.{k} = s.{k}&quot; for k in keys])<br>    update_clause = &quot;, &quot;.join([f&quot;t.{c} = s.{c}&quot; for c in df.columns if c not in keys])<br>    insert_cols = &quot;, &quot;.join(df.columns)<br>    insert_vals = &quot;, &quot;.join([f&quot;s.{c}&quot; for c in df.columns])<br><br>    spark.sql(<br>        f&quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS {target_table}<br>        USING iceberg<br>        AS SELECT * FROM {temp_view} WHERE 1=0<br>        &quot;&quot;&quot;<br>    )<br>    spark.sql(<br>        f&quot;&quot;&quot;<br>        MERGE INTO {target_table} t<br>        USING {temp_view} s<br>        ON {on_clause}<br>        WHEN MATCHED THEN UPDATE SET {update_clause}<br>        WHEN NOT MATCHED THEN INSERT ({insert_cols}) VALUES ({insert_vals})<br>        &quot;&quot;&quot;<br>    )<br><br><br>def replace_table(spark, df, target_table):<br>    temp_view = f&quot;tmp_{target_table.split(&#39;.&#39;)[-1]}&quot;<br>    df.createOrReplaceTempView(temp_view)<br>    sql = f&quot;&quot;&quot;<br>        CREATE OR REPLACE TABLE {target_table}<br>        USING iceberg<br>        AS SELECT * FROM {temp_view}<br>        &quot;&quot;&quot;<br><br>    def force_delete_glue_table() -&gt; None:<br>        parts = target_table.split(&quot;.&quot;)<br>        if len(parts) != 3:<br>            raise ValueError(f&quot;Expected catalog.database.table, got: {target_table}&quot;)<br>        database, table_name = parts[1], parts[2]<br>        if boto3 is not None:<br>            glue = boto3.client(&quot;glue&quot;)<br>            try:<br>                glue.delete_table(DatabaseName=database, Name=table_name)<br>                logger.warning(<br>                    &quot;Deleted stale Glue table metadata for %s.%s via boto3&quot;,<br>                    database,<br>                    table_name,<br>                )<br>                return<br>            except ClientError as delete_err:<br>                code = delete_err.response.get(&quot;Error&quot;, {}).get(&quot;Code&quot;)<br>                if code == &quot;EntityNotFoundException&quot;:<br>                    return<br>                raise<br><br>        # Fallback path when boto3 is not available in the Spark runtime image.<br>        jvm = spark._jvm<br>        glue_client = jvm.software.amazon.awssdk.services.glue.GlueClient.builder().build()<br>        try:<br>            request = (<br>                jvm.software.amazon.awssdk.services.glue.model.DeleteTableRequest.builder()<br>                .databaseName(database)<br>                .name(table_name)<br>                .build()<br>            )<br>            glue_client.deleteTable(request)<br>            logger.warning(<br>                &quot;Deleted stale Glue table metadata for %s.%s via AWS SDK&quot;,<br>                database,<br>                table_name,<br>            )<br>        except Exception as delete_err:  # py4j wraps Java exceptions<br>            if &quot;EntityNotFoundException&quot; in str(delete_err):<br>                return<br>            raise<br>        finally:<br>            glue_client.close()<br><br>    try:<br>        spark.sql(sql)<br>    except Exception as exc:<br>        message = str(exc)<br>        # Self-heal when Glue points to a missing Iceberg metadata.json in S3.<br>        if &quot;Location does not exist&quot; in message or &quot;NoSuchKeyException&quot; in message:<br>            logger.warning(<br>                &quot;Detected stale Iceberg metadata for %s; deleting Glue table and retrying replace&quot;,<br>                target_table,<br>            )<br>            force_delete_glue_table()<br>            spark.sql(sql)<br>            return<br>        raise<br><br><br>def write_table(spark, df, target_table, keys, mode):<br>    if mode == &quot;replace&quot;:<br>        replace_table(spark, df, target_table)<br>        return<br>    merge_table(spark, df, target_table, keys)<br><br><br>def write_export(spark, df, base_path: str):<br>    def split_s3_uri(uri: str) -&gt; tuple[str, str]:<br>        if not uri.startswith(&quot;s3://&quot;):<br>            raise ValueError(f&quot;Expected s3:// URI, got: {uri}&quot;)<br>        without_scheme = uri[5:]<br>        bucket, _, key = without_scheme.partition(&quot;/&quot;)<br>        return bucket, key.rstrip(&quot;/&quot;)<br><br>    def upload_file_to_s3(local_file: Path, s3_uri: str) -&gt; None:<br>        bucket, key_prefix = split_s3_uri(s3_uri)<br>        key = f&quot;{key_prefix}/data.parquet&quot; if key_prefix else &quot;data.parquet&quot;<br>        if boto3 is not None:<br>            s3 = boto3.client(&quot;s3&quot;)<br>            s3.upload_file(str(local_file), bucket, key)<br>            return<br><br>        # Fallback path when boto3 is not available in the Spark runtime image.<br>        # Use AWS Java SDK v1 direct putObject(File) to avoid S3A path semantics.<br>        jvm = spark._jvm<br>        s3_client = jvm.com.amazonaws.services.s3.AmazonS3ClientBuilder.defaultClient()<br>        try:<br>            put_request = jvm.com.amazonaws.services.s3.model.PutObjectRequest(<br>                bucket,<br>                key,<br>                jvm.java.io.File(str(local_file)),<br>            )<br>            s3_client.putObject(put_request)<br>        finally:<br>            s3_client.shutdown()<br><br>    temp_dir = Path(tempfile.mkdtemp(prefix=&quot;hc_rcm_export_&quot;))<br>    try:<br>        local_export_dir = temp_dir / &quot;parquet_out&quot;<br>        (<br>            df.coalesce(1)<br>            .write.mode(&quot;overwrite&quot;)<br>            .parquet(str(local_export_dir))<br>        )<br>        part_files = sorted(local_export_dir.glob(&quot;part-*.parquet&quot;))<br>        if not part_files:<br>            raise RuntimeError(f&quot;No parquet part file found under {local_export_dir}&quot;)<br>        upload_file_to_s3(part_files[0], base_path)<br>        logger.info(&quot;[export] wrote %s&quot;, f&quot;{base_path.rstrip(&#39;/&#39;)}/data.parquet&quot;)<br>    finally:<br>        shutil.rmtree(temp_dir, ignore_errors=True)<br><br><br>def configure_logging() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br><br><br>def log_df_sample(label: str, df, rows: int) -&gt; None:<br>    logger.info(&quot;[%s] columns=%s&quot;, label, &quot;, &quot;.join(df.columns))<br>    for row in df.limit(rows).toJSON().collect():<br>        logger.info(&quot;[%s] %s&quot;, label, row)<br><br><br>def main():<br>    configure_logging()<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--warehouse&quot;, required=True)<br>    parser.add_argument(&quot;--data-bucket&quot;, required=True)<br>    parser.add_argument(&quot;--run-date&quot;, required=True)<br>    parser.add_argument(&quot;--write-mode&quot;, choices=[&quot;merge&quot;, &quot;replace&quot;], default=&quot;merge&quot;)<br>    parser.add_argument(&quot;--sample-rows&quot;, type=int, default=3)<br>    args = parser.parse_args()<br><br>    spark = build_spark(&quot;hc-rcm-silver-to-gold&quot;, args.warehouse)<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br>    run_date = args.run_date<br><br>    claims = spark.table(&quot;glue_catalog.hc_rcm_silver.claims&quot;)<br>    remits = spark.table(&quot;glue_catalog.hc_rcm_silver.remits&quot;)<br>    facilities = spark.table(&quot;glue_catalog.hc_rcm_silver.facilities&quot;)<br>    workqueue = spark.table(&quot;glue_catalog.hc_rcm_silver.workqueue&quot;)<br>    patient_access = spark.table(&quot;glue_catalog.hc_rcm_silver.patient_access&quot;)<br>    log_df_sample(&quot;claims_silver_in&quot;, claims, args.sample_rows)<br>    log_df_sample(&quot;remits_silver_in&quot;, remits, args.sample_rows)<br>    log_df_sample(&quot;facilities_silver_in&quot;, facilities, args.sample_rows)<br>    log_df_sample(&quot;workqueue_silver_in&quot;, workqueue, args.sample_rows)<br>    log_df_sample(&quot;patient_access_silver_in&quot;, patient_access, args.sample_rows)<br><br>    fact = (<br>        claims.alias(&quot;c&quot;)<br>        .join(remits.alias(&quot;r&quot;), F.col(&quot;c.claim_id&quot;) == F.col(&quot;r.claim_id&quot;), &quot;left&quot;)<br>        .join(workqueue.alias(&quot;w&quot;), (F.col(&quot;c.claim_id&quot;) == F.col(&quot;w.claim_id&quot;)) &amp; (F.col(&quot;c.load_run_date&quot;) == F.col(&quot;w.load_run_date&quot;)), &quot;left&quot;)<br>        .join(facilities.alias(&quot;f&quot;), F.col(&quot;c.facility_id&quot;) == F.col(&quot;f.facility_id&quot;), &quot;left&quot;)<br>        .select(<br>            F.col(&quot;c.claim_id&quot;),<br>            F.col(&quot;c.claim_type&quot;),<br>            F.col(&quot;c.facility_id&quot;),<br>            F.col(&quot;f.facility_name&quot;),<br>            F.col(&quot;f.state&quot;).alias(&quot;facility_state&quot;),<br>            F.col(&quot;c.provider_npi&quot;),<br>            F.col(&quot;c.claim_received_at&quot;),<br>            F.col(&quot;r.adjudicated_at&quot;),<br>            F.col(&quot;r.remit_status&quot;),<br>            F.col(&quot;r.denial_reason_code&quot;),<br>            F.col(&quot;w.bottleneck_stage&quot;),<br>            F.col(&quot;w.touch_count&quot;),<br>            F.col(&quot;w.reopened_flag&quot;),<br>            F.col(&quot;c.billed_amount&quot;),<br>            F.col(&quot;c.expected_allowed_amount&quot;),<br>            F.col(&quot;r.paid_amount&quot;),<br>            F.col(&quot;r.patient_responsibility&quot;),<br>            F.col(&quot;r.adjustment_amount&quot;),<br>            F.to_date(&quot;c.claim_received_at&quot;).alias(&quot;metric_date&quot;),<br>        )<br>    ).cache()<br><br>    finance_reporting_daily = (<br>        fact.groupBy(&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;facility_name&quot;, &quot;facility_state&quot;)<br>        .agg(<br>            F.countDistinct(&quot;claim_id&quot;).alias(&quot;claim_count&quot;),<br>            F.sum(&quot;billed_amount&quot;).alias(&quot;total_billed_amount&quot;),<br>            F.sum(&quot;expected_allowed_amount&quot;).alias(&quot;total_expected_allowed_amount&quot;),<br>            F.sum(&quot;paid_amount&quot;).alias(&quot;total_paid_amount&quot;),<br>            F.sum(&quot;patient_responsibility&quot;).alias(&quot;total_patient_responsibility&quot;),<br>            F.sum(&quot;adjustment_amount&quot;).alias(&quot;total_adjustments&quot;),<br>        )<br>        .withColumn(<br>            &quot;net_collection_ratio_proxy&quot;,<br>            F.when(F.col(&quot;total_expected_allowed_amount&quot;) &gt; 0,<br>                   F.col(&quot;total_paid_amount&quot;) / F.col(&quot;total_expected_allowed_amount&quot;)).otherwise(F.lit(None))<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    denial_trends_daily = (<br>        fact.groupBy(&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;facility_name&quot;, &quot;denial_reason_code&quot;)<br>        .agg(<br>            F.countDistinct(&quot;claim_id&quot;).alias(&quot;claims_in_group&quot;),<br>            F.countDistinct(<br>                F.when(F.col(&quot;remit_status&quot;) == &quot;DENIED&quot;, F.col(&quot;claim_id&quot;))<br>            ).alias(&quot;denied_claims&quot;),<br>            F.countDistinct(<br>                F.when(F.col(&quot;remit_status&quot;) == &quot;PARTIAL&quot;, F.col(&quot;claim_id&quot;))<br>            ).alias(&quot;partial_claims&quot;),<br>        )<br>        .withColumn(<br>            &quot;denial_rate&quot;,<br>            F.when(F.col(&quot;claims_in_group&quot;) &gt; 0,<br>                   F.col(&quot;denied_claims&quot;) / F.col(&quot;claims_in_group&quot;)).otherwise(F.lit(None))<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    reimbursement_lag_daily = (<br>        fact.groupBy(&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;facility_name&quot;)<br>        .agg(<br>            F.avg(F.datediff(F.col(&quot;adjudicated_at&quot;), F.col(&quot;claim_received_at&quot;))).alias(&quot;avg_reimbursement_lag_days&quot;),<br>            F.expr(&quot;percentile_approx(datediff(adjudicated_at, claim_received_at), 0.95)&quot;).alias(&quot;p95_reimbursement_lag_days&quot;),<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    facility_operational_efficiency_daily = (<br>        fact.groupBy(&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;facility_name&quot;, &quot;bottleneck_stage&quot;)<br>        .agg(<br>            F.countDistinct(&quot;claim_id&quot;).alias(&quot;claims_touched&quot;),<br>            F.avg(&quot;touch_count&quot;).alias(&quot;avg_touch_count&quot;),<br>            F.avg(F.when(F.col(&quot;reopened_flag&quot;) == 1, 1).otherwise(0)).alias(&quot;rework_rate&quot;),<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    revenue_cycle_kpi_daily = (<br>        fact.groupBy(&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;facility_name&quot;)<br>        .agg(<br>            F.countDistinct(&quot;claim_id&quot;).alias(&quot;claim_count&quot;),<br>            F.countDistinct(<br>                F.when(F.col(&quot;remit_status&quot;) == &quot;DENIED&quot;, F.col(&quot;claim_id&quot;))<br>            ).alias(&quot;denied_claims&quot;),<br>            F.sum(&quot;billed_amount&quot;).alias(&quot;billed_amount&quot;),<br>            F.sum(&quot;expected_allowed_amount&quot;).alias(&quot;expected_allowed_amount&quot;),<br>            F.sum(&quot;paid_amount&quot;).alias(&quot;paid_amount&quot;),<br>            F.avg(F.datediff(F.col(&quot;adjudicated_at&quot;), F.col(&quot;claim_received_at&quot;))).alias(&quot;avg_reimbursement_lag_days&quot;),<br>        )<br>        .withColumn(&quot;denial_rate&quot;, F.when(F.col(&quot;claim_count&quot;) &gt; 0, F.col(&quot;denied_claims&quot;) / F.col(&quot;claim_count&quot;)).otherwise(F.lit(None)))<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    compliance_monitor_daily = (<br>        fact.groupBy(&quot;metric_date&quot;)<br>        .agg(<br>            F.sum(F.when(F.col(&quot;provider_npi&quot;).isNull(), 1).otherwise(0)).alias(&quot;claims_missing_provider_npi&quot;),<br>            F.sum(F.when(F.col(&quot;facility_id&quot;).isNull(), 1).otherwise(0)).alias(&quot;claims_missing_facility_id&quot;),<br>            F.sum(F.when(F.col(&quot;claim_received_at&quot;).isNull() | F.col(&quot;adjudicated_at&quot;).isNull(), 1).otherwise(0)).alias(&quot;claims_missing_dates&quot;),<br>            F.sum(F.when(F.col(&quot;billed_amount&quot;) &lt; 0, 1).otherwise(0)).alias(&quot;negative_billed_records&quot;),<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>    )<br><br>    patient_access_growth_daily = (<br>        patient_access.groupBy(&quot;event_date&quot;, &quot;facility_id&quot;)<br>        .agg(<br>            F.sum(&quot;referred_patients&quot;).alias(&quot;referred_patients&quot;),<br>            F.sum(&quot;scheduled_patients&quot;).alias(&quot;scheduled_patients&quot;),<br>            F.sum(&quot;completed_first_visit&quot;).alias(&quot;completed_first_visit&quot;),<br>            F.avg(&quot;avg_days_to_appointment&quot;).alias(&quot;avg_days_to_appointment&quot;),<br>        )<br>        .withColumn(<br>            &quot;referral_to_visit_conversion_rate&quot;,<br>            F.when(F.col(&quot;referred_patients&quot;) &gt; 0, F.col(&quot;completed_first_visit&quot;) / F.col(&quot;referred_patients&quot;)).otherwise(F.lit(None))<br>        )<br>        .withColumn(&quot;run_date&quot;, F.lit(run_date).cast(&quot;date&quot;))<br>        .withColumnRenamed(&quot;event_date&quot;, &quot;metric_date&quot;)<br>    )<br><br>    write_table(spark, finance_reporting_daily, &quot;glue_catalog.hc_rcm_gold.finance_reporting_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;], args.write_mode)<br>    write_table(spark, denial_trends_daily, &quot;glue_catalog.hc_rcm_gold.denial_trends_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;denial_reason_code&quot;], args.write_mode)<br>    write_table(spark, reimbursement_lag_daily, &quot;glue_catalog.hc_rcm_gold.reimbursement_lag_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;], args.write_mode)<br>    write_table(spark, facility_operational_efficiency_daily, &quot;glue_catalog.hc_rcm_gold.facility_operational_efficiency_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;, &quot;bottleneck_stage&quot;], args.write_mode)<br>    write_table(spark, revenue_cycle_kpi_daily, &quot;glue_catalog.hc_rcm_gold.revenue_cycle_kpi_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;], args.write_mode)<br>    write_table(spark, compliance_monitor_daily, &quot;glue_catalog.hc_rcm_gold.compliance_monitor_daily&quot;, [&quot;metric_date&quot;], args.write_mode)<br>    write_table(spark, patient_access_growth_daily, &quot;glue_catalog.hc_rcm_gold.patient_access_growth_daily&quot;, [&quot;metric_date&quot;, &quot;facility_id&quot;], args.write_mode)<br><br>    export_base = f&quot;s3://{args.data_bucket}/snowflake_exports/{run_date}&quot;<br>    write_export(spark, finance_reporting_daily, f&quot;{export_base}/finance_reporting_daily&quot;)<br>    write_export(spark, denial_trends_daily, f&quot;{export_base}/denial_trends_daily&quot;)<br>    write_export(spark, reimbursement_lag_daily, f&quot;{export_base}/reimbursement_lag_daily&quot;)<br>    write_export(spark, facility_operational_efficiency_daily, f&quot;{export_base}/facility_operational_efficiency_daily&quot;)<br>    write_export(spark, revenue_cycle_kpi_daily, f&quot;{export_base}/revenue_cycle_kpi_daily&quot;)<br>    write_export(spark, compliance_monitor_daily, f&quot;{export_base}/compliance_monitor_daily&quot;)<br>    write_export(spark, patient_access_growth_daily, f&quot;{export_base}/patient_access_growth_daily&quot;)<br>    log_df_sample(&quot;finance_reporting_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.finance_reporting_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;denial_trends_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.denial_trends_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;reimbursement_lag_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.reimbursement_lag_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;facility_operational_efficiency_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.facility_operational_efficiency_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;revenue_cycle_kpi_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.revenue_cycle_kpi_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;compliance_monitor_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.compliance_monitor_daily&quot;), args.sample_rows)<br>    log_df_sample(&quot;patient_access_growth_daily_out&quot;, spark.table(&quot;glue_catalog.hc_rcm_gold.patient_access_growth_daily&quot;), args.sample_rows)<br><br>    spark.stop()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Quality checks: spark/quality_checks.py</li></ul><pre>import argparse<br>import json<br>import logging<br><br>import yaml<br>from pyspark.sql import SparkSession, functions as F<br><br>logger = logging.getLogger(__name__)<br><br><br>def build_spark(app_name: str, warehouse: str) -&gt; SparkSession:<br>    return (<br>        SparkSession.builder.appName(app_name)<br>        .config(&quot;spark.sql.catalog.glue_catalog&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.warehouse&quot;, warehouse)<br>        .config(&quot;spark.sql.catalog.glue_catalog.catalog-impl&quot;, &quot;org.apache.iceberg.aws.glue.GlueCatalog&quot;)<br>        .config(&quot;spark.sql.catalog.glue_catalog.io-impl&quot;, &quot;org.apache.iceberg.aws.s3.S3FileIO&quot;)<br>        .config(&quot;spark.sql.extensions&quot;, &quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)<br>        .config(&quot;spark.sql.shuffle.partitions&quot;, &quot;32&quot;)<br>        .getOrCreate()<br>    )<br><br><br>def configure_logging() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br><br><br>def log_df_sample(label: str, df, rows: int) -&gt; None:<br>    logger.info(&quot;[%s] columns=%s&quot;, label, &quot;, &quot;.join(df.columns))<br>    for row in df.limit(rows).toJSON().collect():<br>        logger.info(&quot;[%s] %s&quot;, label, row)<br><br><br>def main():<br>    configure_logging()<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--warehouse&quot;, required=True)<br>    parser.add_argument(&quot;--contracts&quot;, required=True)<br>    parser.add_argument(&quot;--sample-rows&quot;, type=int, default=3)<br>    args = parser.parse_args()<br><br>    with open(args.contracts, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        contracts = yaml.safe_load(f)<br><br>    spark = build_spark(&quot;hc-rcm-quality-checks&quot;, args.warehouse)<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br><br>    claims = spark.table(&quot;glue_catalog.hc_rcm_silver.claims&quot;)<br>    remits = spark.table(&quot;glue_catalog.hc_rcm_silver.remits&quot;)<br>    kpi = spark.table(&quot;glue_catalog.hc_rcm_gold.revenue_cycle_kpi_daily&quot;)<br>    log_df_sample(&quot;claims_silver_in&quot;, claims, args.sample_rows)<br>    log_df_sample(&quot;remits_silver_in&quot;, remits, args.sample_rows)<br>    log_df_sample(&quot;kpi_gold_in&quot;, kpi, args.sample_rows)<br><br>    results = {}<br><br>    duplicate_claim_ids = (<br>        claims.groupBy(&quot;claim_id&quot;).count().filter(F.col(&quot;count&quot;) &gt; 1).count()<br>    )<br>    results[&quot;silver_claims_duplicate_claim_id&quot;] = duplicate_claim_ids<br><br>    negative_billed = claims.filter(F.col(&quot;billed_amount&quot;) &lt; 0).count()<br>    results[&quot;silver_claims_negative_billed_amount&quot;] = negative_billed<br><br>    total_claims = claims.count()<br>    missing_provider = claims.filter(F.col(&quot;provider_npi&quot;).isNull()).count()<br>    missing_provider_pct = 0 if total_claims == 0 else missing_provider / total_claims<br>    results[&quot;silver_claims_missing_provider_npi_pct&quot;] = missing_provider_pct<br><br>    missing_claim_id_remits = remits.filter(F.col(&quot;claim_id&quot;).isNull()).count()<br>    results[&quot;silver_remits_missing_claim_id&quot;] = missing_claim_id_remits<br><br>    avg_lag = kpi.agg(F.avg(&quot;avg_reimbursement_lag_days&quot;).alias(&quot;avg_lag&quot;)).collect()[0][&quot;avg_lag&quot;] or 0<br>    denial_agg = (<br>        kpi.agg(<br>            F.max(&quot;denial_rate&quot;).alias(&quot;max_denial&quot;),<br>            F.sum(F.coalesce(F.col(&quot;denied_claims&quot;), F.lit(0))).alias(&quot;sum_denied_claims&quot;),<br>            F.sum(F.coalesce(F.col(&quot;claim_count&quot;), F.lit(0))).alias(&quot;sum_claim_count&quot;),<br>        )<br>        .collect()[0]<br>    )<br>    max_denial = denial_agg[&quot;max_denial&quot;] or 0<br>    total_denied_claims = float(denial_agg[&quot;sum_denied_claims&quot;] or 0)<br>    total_claim_count = float(denial_agg[&quot;sum_claim_count&quot;] or 0)<br>    overall_denial_rate = 0.0 if total_claim_count == 0 else total_denied_claims / total_claim_count<br>    results[&quot;gold_reimbursement_lag_days_avg&quot;] = float(avg_lag)<br>    results[&quot;gold_denial_rate_max&quot;] = float(max_denial)<br>    results[&quot;gold_denial_rate_overall&quot;] = float(overall_denial_rate)<br><br>    thresholds = contracts[&quot;thresholds&quot;]<br>    failures = []<br><br>    if results[&quot;silver_claims_duplicate_claim_id&quot;] &gt; thresholds[&quot;silver_claims_duplicate_claim_id_max&quot;]:<br>        failures.append(&quot;duplicate claim ids&quot;)<br>    if results[&quot;silver_claims_negative_billed_amount&quot;] &gt; thresholds[&quot;silver_claims_negative_billed_amount_max&quot;]:<br>        failures.append(&quot;negative billed amounts&quot;)<br>    if results[&quot;silver_claims_missing_provider_npi_pct&quot;] &gt; thresholds[&quot;silver_claims_missing_provider_npi_pct_max&quot;]:<br>        failures.append(&quot;provider npi null rate too high&quot;)<br>    if results[&quot;silver_remits_missing_claim_id&quot;] &gt; thresholds[&quot;silver_remits_missing_claim_id_max&quot;]:<br>        failures.append(&quot;remits missing claim id&quot;)<br>    if results[&quot;gold_reimbursement_lag_days_avg&quot;] &gt; thresholds[&quot;gold_reimbursement_lag_days_max_avg&quot;]:<br>        failures.append(&quot;average reimbursement lag too high&quot;)<br>    if results[&quot;gold_denial_rate_overall&quot;] &gt; thresholds[&quot;gold_denial_rate_pct_max&quot;]:<br>        failures.append(&quot;overall denial rate above threshold&quot;)<br><br>    print(json.dumps({&quot;results&quot;: results, &quot;failures&quot;: failures}, indent=2))<br>    spark.stop()<br><br>    if failures:<br>        raise SystemExit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Snowflake loader: apps/snowflake/load_gold_exports.py</li></ul><pre>import argparse<br>import logging<br>import os<br>from datetime import datetime<br>from pathlib import Path<br><br>import snowflake.connector<br><br><br>logger = logging.getLogger(__name__)<br><br><br>def require_env(name: str) -&gt; str:<br>    value = os.getenv(name, &quot;&quot;).strip()<br>    if not value:<br>        raise ValueError(f&quot;Missing required environment variable: {name}&quot;)<br>    return value<br><br><br>def render_sql(template_sql: str, run_date: str) -&gt; str:<br>    return (<br>        template_sql.replace(&quot;{{ ds }}&quot;, run_date)<br>        .replace(&quot;{{ds}}&quot;, run_date)<br>        .replace(&quot;{{ run_date }}&quot;, run_date)<br>        .replace(&quot;{{run_date}}&quot;, run_date)<br>    )<br><br><br>def validate_run_date(run_date: str) -&gt; str:<br>    datetime.strptime(run_date, &quot;%Y-%m-%d&quot;)<br>    return run_date<br><br><br>def main() -&gt; None:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s | %(levelname)s | %(message)s&quot;,<br>    )<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(&quot;--run-date&quot;, required=True, help=&quot;YYYY-MM-DD&quot;)<br>    parser.add_argument(<br>        &quot;--sql-file&quot;,<br>        default=&quot;snowflake/03_copy_and_views.sql&quot;,<br>        help=&quot;Path to SQL template with {{ ds }} placeholder&quot;,<br>    )<br>    args = parser.parse_args()<br><br>    run_date = validate_run_date(args.run_date)<br>    sql_path = Path(args.sql_file)<br>    if not sql_path.exists():<br>        raise FileNotFoundError(f&quot;SQL file not found: {sql_path}&quot;)<br><br>    account = require_env(&quot;SNOWFLAKE_ACCOUNT&quot;)<br>    user = require_env(&quot;SNOWFLAKE_USER&quot;)<br>    password = require_env(&quot;SNOWFLAKE_PASSWORD&quot;)<br>    warehouse = require_env(&quot;SNOWFLAKE_WAREHOUSE&quot;)<br>    database = require_env(&quot;SNOWFLAKE_DATABASE&quot;)<br>    schema = require_env(&quot;SNOWFLAKE_SCHEMA&quot;)<br>    role = require_env(&quot;SNOWFLAKE_ROLE&quot;)<br><br>    template_sql = sql_path.read_text(encoding=&quot;utf-8&quot;)<br>    rendered_sql = render_sql(template_sql, run_date)<br>    logger.info(&quot;Loading Snowflake gold exports for run_date=%s&quot;, run_date)<br><br>    conn = snowflake.connector.connect(<br>        account=account,<br>        user=user,<br>        password=password,<br>        warehouse=warehouse,<br>        database=database,<br>        schema=schema,<br>        role=role,<br>        autocommit=True,<br>    )<br><br>    try:<br>        for cursor in conn.execute_string(rendered_sql, remove_comments=False):<br>            logger.info(<br>                &quot;Executed Snowflake statement | query_id=%s | rowcount=%s&quot;,<br>                cursor.sfqid,<br>                cursor.rowcount,<br>            )<br>            cursor.close()<br>    finally:<br>        conn.close()<br><br>    logger.info(&quot;Snowflake load completed for run_date=%s&quot;, run_date)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Snowflake SQL setup/load:</p><ul><li>snowflake/01_security_and_warehouse.sql</li></ul><pre>USE ROLE ACCOUNTADMIN;<br><br>CREATE OR REPLACE WAREHOUSE HC_RCM_WH<br>  WAREHOUSE_SIZE = &#39;XSMALL&#39;<br>  AUTO_SUSPEND = 60<br>  AUTO_RESUME = TRUE<br>  INITIALLY_SUSPENDED = TRUE;<br><br>CREATE DATABASE IF NOT EXISTS HC_RCM;<br>CREATE SCHEMA IF NOT EXISTS HC_RCM.RAW;<br>CREATE SCHEMA IF NOT EXISTS HC_RCM.CURATED;<br>CREATE SCHEMA IF NOT EXISTS HC_RCM.SECURITY;<br><br>CREATE ROLE IF NOT EXISTS HC_RCM_INGEST_ROLE;<br>CREATE ROLE IF NOT EXISTS HC_RCM_ANALYST_ROLE;<br><br>GRANT USAGE ON WAREHOUSE HC_RCM_WH TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT USAGE ON WAREHOUSE HC_RCM_WH TO ROLE HC_RCM_ANALYST_ROLE;<br><br>GRANT USAGE ON DATABASE HC_RCM TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT USAGE ON DATABASE HC_RCM TO ROLE HC_RCM_ANALYST_ROLE;<br>GRANT USAGE ON ALL SCHEMAS IN DATABASE HC_RCM TO ROLE HC_RCM_ANALYST_ROLE;<br>GRANT USAGE ON SCHEMA HC_RCM.RAW TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT USAGE ON SCHEMA HC_RCM.CURATED TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT CREATE TABLE, CREATE STAGE, CREATE FILE FORMAT ON SCHEMA HC_RCM.RAW TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT CREATE TABLE, CREATE VIEW ON SCHEMA HC_RCM.CURATED TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT SELECT, INSERT, DELETE ON ALL TABLES IN SCHEMA HC_RCM.CURATED TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT SELECT, INSERT, DELETE ON FUTURE TABLES IN SCHEMA HC_RCM.CURATED TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT ROLE HC_RCM_INGEST_ROLE TO USER SHITANSHUM96;<br>GRANT ROLE HC_RCM_ANALYST_ROLE TO USER SHITANSHUM96;<br><br>-- Example masking policy for sensitive identifiers if you later load patient-level data.<br>CREATE OR REPLACE MASKING POLICY HC_RCM.SECURITY.MASK_STRING AS (val STRING) RETURNS STRING -&gt;<br>  CASE<br>    WHEN CURRENT_ROLE() IN (&#39;ACCOUNTADMIN&#39;, &#39;HC_RCM_INGEST_ROLE&#39;) THEN val<br>    ELSE CONCAT(REPEAT(&#39;*&#39;, GREATEST(LENGTH(val)-4, 0)), RIGHT(val, 4))<br>  END;</pre><ul><li>snowflake/02_stages_and_tables.sql</li></ul><pre>USE ROLE ACCOUNTADMIN;<br>USE DATABASE HC_RCM;<br>USE SCHEMA RAW;<br><br>CREATE OR REPLACE FILE FORMAT PARQUET_FF TYPE = PARQUET;<br><br>-- Create this integration only after you create the AWS-side IAM role for Snowflake.<br>-- Replace &lt;AWS_ACCOUNT_ID&gt; and &lt;DATA_BUCKET&gt; before executing.<br>CREATE OR REPLACE STORAGE INTEGRATION HC_RCM_S3_INT<br>  TYPE = EXTERNAL_STAGE<br>  STORAGE_PROVIDER = S3<br>  ENABLED = TRUE<br>  STORAGE_AWS_ROLE_ARN = &#39;arn:aws:iam::799619129387:role/hc-rcm-snowflake-stage-role&#39;<br>  STORAGE_ALLOWED_LOCATIONS = (&#39;s3://hc-rcm-demo-data-123456/snowflake_exports/&#39;);<br><br>CREATE OR REPLACE STAGE HC_RCM.RAW.RCM_GOLD_STAGE<br>  URL = &#39;s3://hc-rcm-demo-data-123456/snowflake_exports/&#39;<br>  STORAGE_INTEGRATION = HC_RCM_S3_INT<br>  FILE_FORMAT = HC_RCM.RAW.PARQUET_FF;<br><br>GRANT USAGE ON INTEGRATION HC_RCM_S3_INT TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT USAGE ON FILE FORMAT HC_RCM.RAW.PARQUET_FF TO ROLE HC_RCM_INGEST_ROLE;<br>GRANT USAGE, READ ON STAGE HC_RCM.RAW.RCM_GOLD_STAGE TO ROLE HC_RCM_INGEST_ROLE;<br><br>USE SCHEMA CURATED;<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.FINANCE_REPORTING_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  facility_name STRING,<br>  facility_state STRING,<br>  claim_count NUMBER,<br>  total_billed_amount NUMBER(18,2),<br>  total_expected_allowed_amount NUMBER(18,2),<br>  total_paid_amount NUMBER(18,2),<br>  total_patient_responsibility NUMBER(18,2),<br>  total_adjustments NUMBER(18,2),<br>  net_collection_ratio_proxy FLOAT,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.DENIAL_TRENDS_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  facility_name STRING,<br>  denial_reason_code STRING,<br>  claims_in_group NUMBER,<br>  denied_claims NUMBER,<br>  partial_claims NUMBER,<br>  denial_rate FLOAT,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.REIMBURSEMENT_LAG_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  facility_name STRING,<br>  avg_reimbursement_lag_days FLOAT,<br>  p95_reimbursement_lag_days FLOAT,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.FACILITY_OPERATIONAL_EFFICIENCY_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  facility_name STRING,<br>  bottleneck_stage STRING,<br>  claims_touched NUMBER,<br>  avg_touch_count FLOAT,<br>  rework_rate FLOAT,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  facility_name STRING,<br>  claim_count NUMBER,<br>  denied_claims NUMBER,<br>  billed_amount NUMBER(18,2),<br>  expected_allowed_amount NUMBER(18,2),<br>  paid_amount NUMBER(18,2),<br>  avg_reimbursement_lag_days FLOAT,<br>  denial_rate FLOAT,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.COMPLIANCE_MONITOR_DAILY (<br>  metric_date DATE,<br>  claims_missing_provider_npi NUMBER,<br>  claims_missing_facility_id NUMBER,<br>  claims_missing_dates NUMBER,<br>  negative_billed_records NUMBER,<br>  run_date DATE<br>);<br><br>CREATE OR REPLACE TABLE HC_RCM.CURATED.PATIENT_ACCESS_GROWTH_DAILY (<br>  metric_date DATE,<br>  facility_id STRING,<br>  referred_patients NUMBER,<br>  scheduled_patients NUMBER,<br>  completed_first_visit NUMBER,<br>  avg_days_to_appointment FLOAT,<br>  referral_to_visit_conversion_rate FLOAT,<br>  run_date DATE<br>);</pre><ul><li>snowflake/03_copy_and_views.sql</li></ul><pre>USE ROLE HC_RCM_INGEST_ROLE;<br>USE WAREHOUSE HC_RCM_WH;<br>USE DATABASE HC_RCM;<br>USE SCHEMA CURATED;<br><br>DELETE FROM HC_RCM.CURATED.FINANCE_REPORTING_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.FINANCE_REPORTING_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:facility_name::STRING,<br>    $1:facility_state::STRING,<br>    $1:claim_count::NUMBER,<br>    $1:total_billed_amount::NUMBER(18,2),<br>    $1:total_expected_allowed_amount::NUMBER(18,2),<br>    $1:total_paid_amount::NUMBER(18,2),<br>    $1:total_patient_responsibility::NUMBER(18,2),<br>    $1:total_adjustments::NUMBER(18,2),<br>    $1:net_collection_ratio_proxy::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/finance_reporting_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.DENIAL_TRENDS_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.DENIAL_TRENDS_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:facility_name::STRING,<br>    $1:denial_reason_code::STRING,<br>    $1:claims_in_group::NUMBER,<br>    $1:denied_claims::NUMBER,<br>    $1:partial_claims::NUMBER,<br>    $1:denial_rate::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/denial_trends_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.REIMBURSEMENT_LAG_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.REIMBURSEMENT_LAG_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:facility_name::STRING,<br>    $1:avg_reimbursement_lag_days::FLOAT,<br>    $1:p95_reimbursement_lag_days::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/reimbursement_lag_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.FACILITY_OPERATIONAL_EFFICIENCY_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.FACILITY_OPERATIONAL_EFFICIENCY_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:facility_name::STRING,<br>    $1:bottleneck_stage::STRING,<br>    $1:claims_touched::NUMBER,<br>    $1:avg_touch_count::FLOAT,<br>    $1:rework_rate::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/facility_operational_efficiency_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:facility_name::STRING,<br>    $1:claim_count::NUMBER,<br>    $1:denied_claims::NUMBER,<br>    $1:billed_amount::NUMBER(18,2),<br>    $1:expected_allowed_amount::NUMBER(18,2),<br>    $1:paid_amount::NUMBER(18,2),<br>    $1:avg_reimbursement_lag_days::FLOAT,<br>    $1:denial_rate::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/revenue_cycle_kpi_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.COMPLIANCE_MONITOR_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.COMPLIANCE_MONITOR_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:claims_missing_provider_npi::NUMBER,<br>    $1:claims_missing_facility_id::NUMBER,<br>    $1:claims_missing_dates::NUMBER,<br>    $1:negative_billed_records::NUMBER,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/compliance_monitor_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>DELETE FROM HC_RCM.CURATED.PATIENT_ACCESS_GROWTH_DAILY WHERE run_date = TO_DATE(&#39;{{ ds }}&#39;);<br>COPY INTO HC_RCM.CURATED.PATIENT_ACCESS_GROWTH_DAILY<br>FROM (<br>  SELECT<br>    $1:metric_date::DATE,<br>    $1:facility_id::STRING,<br>    $1:referred_patients::NUMBER,<br>    $1:scheduled_patients::NUMBER,<br>    $1:completed_first_visit::NUMBER,<br>    $1:avg_days_to_appointment::FLOAT,<br>    $1:referral_to_visit_conversion_rate::FLOAT,<br>    $1:run_date::DATE<br>  FROM @HC_RCM.RAW.RCM_GOLD_STAGE/{{ ds }}/patient_access_growth_daily (PATTERN =&gt; &#39;.*[.]parquet&#39;)<br>)<br>FILE_FORMAT = (FORMAT_NAME = &#39;HC_RCM.RAW.PARQUET_FF&#39;) FORCE = TRUE;<br><br>CREATE OR REPLACE VIEW HC_RCM.CURATED.VW_EXECUTIVE_DAILY AS<br>WITH latest_kpi AS (<br>  SELECT *<br>  FROM HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY<br>  QUALIFY ROW_NUMBER() OVER (PARTITION BY metric_date, facility_id ORDER BY run_date DESC) = 1<br>),<br>latest_finance AS (<br>  SELECT *<br>  FROM HC_RCM.CURATED.FINANCE_REPORTING_DAILY<br>  QUALIFY ROW_NUMBER() OVER (PARTITION BY metric_date, facility_id ORDER BY run_date DESC) = 1<br>)<br>SELECT<br>  k.metric_date,<br>  k.facility_id,<br>  k.facility_name,<br>  k.claim_count,<br>  k.denial_rate,<br>  k.avg_reimbursement_lag_days,<br>  f.net_collection_ratio_proxy<br>FROM latest_kpi k<br>LEFT JOIN latest_finance f<br>  ON k.metric_date = f.metric_date AND k.facility_id = f.facility_id;</pre><p>Terraform:</p><ul><li>infra/terraform/main.tf</li></ul><pre>locals {<br>  common_tags = {<br>    Project     = var.project<br>    Environment = &quot;demo&quot;<br>    ManagedBy   = &quot;terraform&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;data&quot; {<br>  bucket        = var.data_bucket_name<br>  force_destroy = true<br>  tags          = local.common_tags<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;data&quot; {<br>  bucket = aws_s3_bucket.data.id<br><br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;data&quot; {<br>  bucket = aws_s3_bucket.data.id<br><br>  rule {<br>    apply_server_side_encryption_by_default {<br>      sse_algorithm = &quot;AES256&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;data&quot; {<br>  bucket                  = aws_s3_bucket.data.id<br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_s3_bucket&quot; &quot;artifacts&quot; {<br>  bucket        = var.artifact_bucket_name<br>  force_destroy = true<br>  tags          = local.common_tags<br>}<br><br>resource &quot;aws_s3_bucket_versioning&quot; &quot;artifacts&quot; {<br>  bucket = aws_s3_bucket.artifacts.id<br><br>  versioning_configuration {<br>    status = &quot;Enabled&quot;<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;artifacts&quot; {<br>  bucket = aws_s3_bucket.artifacts.id<br><br>  rule {<br>    apply_server_side_encryption_by_default {<br>      sse_algorithm = &quot;AES256&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_s3_bucket_public_access_block&quot; &quot;artifacts&quot; {<br>  bucket                  = aws_s3_bucket.artifacts.id<br>  block_public_acls       = true<br>  block_public_policy     = true<br>  ignore_public_acls      = true<br>  restrict_public_buckets = true<br>}<br><br>resource &quot;aws_glue_catalog_database&quot; &quot;this&quot; {<br>  name = var.glue_database<br>}<br><br>resource &quot;aws_sns_topic&quot; &quot;alerts&quot; {<br>  name = &quot;${var.project}-alerts&quot;<br>  tags = local.common_tags<br>}<br><br>resource &quot;aws_sns_topic_subscription&quot; &quot;email&quot; {<br>  count     = var.alert_email == &quot;&quot; ? 0 : 1<br>  topic_arn = aws_sns_topic.alerts.arn<br>  protocol  = &quot;email&quot;<br>  endpoint  = var.alert_email<br>}</pre><ul><li>infra/terraform/tf_with_aws_login.sh</li></ul><pre>#!/usr/bin/env bash<br>set -euo pipefail<br><br>if [[ $# -lt 1 ]]; then<br>  echo &quot;Usage: ./tf_with_aws_login.sh &lt;terraform-subcommand&gt; [args...]&quot; &gt;&amp;2<br>  echo &quot;Example: ./tf_with_aws_login.sh plan&quot; &gt;&amp;2<br>  exit 1<br>fi<br><br>cmd=&quot;$1&quot;<br>shift<br><br>profile=&quot;${AWS_PROFILE:-default}&quot;<br><br># If credentials are already present (for example in CI), reuse them.<br># Otherwise export from the local AWS profile login session.<br>if [[ -z &quot;${AWS_ACCESS_KEY_ID:-}&quot; || -z &quot;${AWS_SECRET_ACCESS_KEY:-}&quot; ]]; then<br>  eval &quot;$(aws configure export-credentials --profile &quot;$profile&quot; --format env)&quot;<br>fi<br><br># Prevent slow IMDS fallback on local machines with no instance role.<br>export AWS_EC2_METADATA_DISABLED=true<br><br>unset AWS_PROFILE AWS_DEFAULT_PROFILE<br><br>case &quot;$cmd&quot; in<br>  plan|apply|destroy)<br>    terraform &quot;$cmd&quot; -var=&#39;aws_profile=&#39; &quot;$@&quot;<br>    ;;<br>  *)<br>    terraform &quot;$cmd&quot; &quot;$@&quot;<br>    ;;<br>esac</pre><h4>#6 Understanding Data Layers</h4><p>Think of the platform as three data quality zones:</p><ul><li><strong>Bronze:</strong> raw landed files exactly as vendor-style feeds arrive in S3.</li><li><strong>Silver: </strong>cleaned and standardized Iceberg tables with typed columns and deduplication.</li><li><strong>Gold: </strong>business KPI tables for finance, operations, and leadership reporting.</li></ul><p>Why this matters:</p><ul><li>If a KPI looks wrong, you can trace it back from Gold to Silver to Bronze.</li><li>If upstream format changes, data contracts catch it before business tables are corrupted.</li><li>You keep both replayability (Bronze) and usability (Gold).</li></ul><h4>#7 How each DAG task works</h4><ul><li><strong>download_public_raw:</strong> downloads public files using chunked streaming, resume logic, and progress bars. It also pulls NPPES and hospital reference files required downstream.</li><li><strong>seed_public_data:</strong> reads big raw CSVs in chunks, samples claims per claim type, normalizes IDs/dates, and enriches with beneficiary/provider/facility context.</li><li><strong>build_vendor_feeds: </strong>converts seed outputs into realistic operational feeds: SFTP-style CSV feeds for claims/remits/reference tables, Portal-style ZIP feeds for the work queue, and patient access.</li><li><strong>ingest_vendor_feeds_to_bronze:</strong> uploads feed files into Bronze S3 prefixes and writes MD5-based control manifests so repeated payloads are skipped safely.</li><li><strong>bronze_to_silver:</strong> reads Bronze files from S3, applies required-column checks from config/data_contracts.yaml, standardizes schema, and writes Iceberg Silver tables.</li></ul><pre># config/data_contracts.yaml<br><br>raw_claims:<br>  required_columns:<br>    - claim_id<br>    - patient_id<br>    - claim_type<br>    - facility_id<br>    - provider_npi<br>    - service_from_date<br>    - service_thru_date<br>    - claim_received_at<br>    - billed_amount<br>    - expected_allowed_amount<br>    - source_system<br><br>raw_remits:<br>  required_columns:<br>    - remittance_id<br>    - claim_id<br>    - adjudicated_at<br>    - remit_status<br>    - paid_amount<br>    - patient_responsibility<br>    - adjustment_amount<br><br>raw_workqueue:<br>  required_columns:<br>    - claim_id<br>    - queue_name<br>    - bottleneck_stage<br>    - aging_bucket<br>    - last_touched_at<br><br>raw_patient_access:<br>  required_columns:<br>    - facility_id<br>    - event_date<br>    - referred_patients<br>    - scheduled_patients<br>    - completed_first_visit<br>    - avg_days_to_appointment<br><br>thresholds:<br>  silver_claims_duplicate_claim_id_max: 0<br>  silver_claims_negative_billed_amount_max: 0<br>  silver_claims_missing_provider_npi_pct_max: 0.25<br>  silver_remits_missing_claim_id_max: 0<br>  gold_reimbursement_lag_days_max_avg: 90<br>  gold_denial_rate_pct_max: 0.50</pre><ul><li><strong>silver_to_gold:</strong> joins claims/remits/workqueue/facilities/patient-access data, computes daily KPI aggregates, writes Gold Iceberg tables, then exports one parquet file per KPI to s3://.../snowflake_exports/&lt;run_date&gt;/....</li><li><strong>quality_checks:</strong> enforces threshold-based checks like duplicate claims, null provider rates, denial-rate bounds, and reimbursement lag limits. If thresholds are breached, the task fails.</li><li><strong>load_gold_to_snowflake:</strong> renders snowflake/03_copy_and_views.sql with the DAG run date and executes Snowflake COPY INTO commands. This makes Snowflake part of the required success path.</li></ul><h3>Step 0: Prerequisites</h3><p>Install and verify:</p><ul><li>Python 3.11+ (project currently uses local venv with Python 3.12 too)</li><li>Docker + Docker Compose</li><li>AWS CLI v2</li><li>Terraform 1.6+</li><li>A Snowflake account (trial is fine)</li></ul><p>You also need AWS permissions to create:</p><ul><li>S3 buckets</li><li>Glue catalog database</li><li>SNS topic</li><li>IAM role/policies for Snowflake external stage</li></ul><h3>Step 1: Provision minimal AWS infra (S3 + Glue + SNS)</h3><ul><li>infra/terraform/providers.tf</li></ul><pre>terraform {<br>  required_version = &quot;&gt;= 1.7.0&quot;<br><br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.90&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  profile = var.aws_profile != &quot;&quot; ? var.aws_profile : null<br>  region  = var.aws_region<br>}</pre><ul><li>infra/terraform/variables.tf</li></ul><pre>variable &quot;aws_profile&quot; {<br>  type    = string<br>  default = &quot;&quot;<br>}<br><br>variable &quot;aws_region&quot; {<br>  type = string<br>}<br><br>variable &quot;project&quot; {<br>  type    = string<br>  default = &quot;hc-rcm&quot;<br>}<br><br>variable &quot;data_bucket_name&quot; {<br>  type = string<br>}<br><br>variable &quot;artifact_bucket_name&quot; {<br>  type = string<br>}<br><br>variable &quot;glue_database&quot; {<br>  type    = string<br>  default = &quot;hc_rcm&quot;<br>}<br><br>variable &quot;alert_email&quot; {<br>  type    = string<br>  default = &quot;&quot;<br>}</pre><ul><li>infra/terraform/outputs.tf</li></ul><pre>output &quot;data_bucket&quot; {<br>  value = aws_s3_bucket.data.bucket<br>}<br><br>output &quot;artifact_bucket&quot; {<br>  value = aws_s3_bucket.artifacts.bucket<br>}<br><br>output &quot;glue_database&quot; {<br>  value = aws_glue_catalog_database.this.name<br>}<br><br>output &quot;alerts_sns_topic_arn&quot; {<br>  value = aws_sns_topic.alerts.arn<br>}</pre><ul><li>infra/terraform/terraform.tfvars.example</li></ul><pre>aws_profile          = &quot;default&quot;<br>aws_region           = &quot;us-east-1&quot;<br>project              = &quot;hc-rcm&quot;<br>data_bucket_name     = &quot;hc-rcm-demo-data-123456&quot;<br>artifact_bucket_name = &quot;hc-rcm-demo-artifacts-123456&quot;<br>glue_database        = &quot;hc_rcm&quot;<br>alert_email          = &quot;you@example.com&quot;</pre><pre>cd /home/Projects/healthcare-rcm-platform/infra/terraform<br>cp terraform.tfvars.example terraform.tfvars<br># Edit terraform.tfvars values if needed<br><br>export AWS_PROFILE=sre-mini-admin<br><br>aws login<br><br>./tf_with_aws_login.sh init<br>./tf_with_aws_login.sh plan -out=tfplan<br>./tf_with_aws_login.sh apply tfplan</pre><p>What this creates:</p><ul><li>Data bucket (Bronze/Iceberg/Snowflake exports)</li><li>Artifact bucket</li><li>Glue database</li><li>SNS topic for task-failure notifications</li></ul><h3>Step 2: Capture Terraform outputs</h3><pre>cd /home/Projects/healthcare-rcm-platform/infra/terraform<br><br>DATA_BUCKET=$(./tf_with_aws_login.sh output -raw data_bucket)<br>ARTIFACT_BUCKET=$(./tf_with_aws_login.sh output -raw artifact_bucket)<br>GLUE_DATABASE=$(./tf_with_aws_login.sh output -raw glue_database)<br>ALERT_SNS_TOPIC_ARN=$(./tf_with_aws_login.sh output -raw alerts_sns_topic_arn)<br>AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text --profile &quot;$AWS_PROFILE&quot;)<br><br>echo &quot;$DATA_BUCKET&quot;<br>echo &quot;$ARTIFACT_BUCKET&quot;<br>echo &quot;$GLUE_DATABASE&quot;<br>echo &quot;$ALERT_SNS_TOPIC_ARN&quot;<br>echo &quot;$AWS_ACCOUNT_ID&quot;</pre><h3>Step 3: Prepare the local environment file</h3><ul><li>.env.example</li></ul><pre>AWS_REGION=us-east-1<br>AWS_DEFAULT_REGION=us-east-1<br>AWS_PROFILE=default<br><br>DATA_BUCKET=hc-rcm-demo-data<br>ARTIFACT_BUCKET=hc-rcm-demo-artifacts<br>GLUE_DATABASE=hc_rcm<br>ICEBERG_WAREHOUSE=s3://hc-rcm-demo-data/iceberg/<br><br>RAW_INPUT_DIR=./data/public_raw<br>SEED_OUTPUT_DIR=./data/public_seed<br>VENDOR_FEED_DIR=./data/vendor_feeds<br>RAW_DOWNLOAD_CHUNK_MB=8<br><br>SPARK_LOCAL_MASTER=local[2]<br>SPARK_LOCAL_WRITE_MODE=replace<br>SPARK_PACKAGES=org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.6.1,org.apache.iceberg:iceberg-aws-bundle:1.6.1,org.apache.hadoop:hadoop-aws:3.3.4<br>SPARK_DRIVER_MEMORY=2g<br>SPARK_EXECUTOR_MEMORY=4g<br>SPARK_SHUFFLE_PARTITIONS=64<br>SPARK_CONTAINER_CPUS=2.0<br>SPARK_CONTAINER_MEM_LIMIT=6g<br><br>AIRFLOW_HOME=./.airflow<br>AIRFLOW__CORE__DAGS_FOLDER=./airflow/dags<br>AIRFLOW__CORE__PLUGINS_FOLDER=./airflow/plugins<br>AIRFLOW__CORE__LOAD_EXAMPLES=False<br>ALERT_SNS_TOPIC_ARN=<br>SNOWFLAKE_LOAD_SQL=snowflake/03_copy_and_views.sql<br><br>SNOWFLAKE_ACCOUNT=fexsupu-zsc06105<br>SNOWFLAKE_USER=shitanshum96<br>SNOWFLAKE_PASSWORD=Snowflake@1911<br>SNOWFLAKE_WAREHOUSE=HC_RCM_WH<br>SNOWFLAKE_DATABASE=HC_RCM<br>SNOWFLAKE_SCHEMA=CURATED<br>SNOWFLAKE_ROLE=HC_RCM_INGEST_ROLE</pre><pre>cd /home/Projects/healthcare-rcm-platform<br>cp .env.example .env</pre><p>Update .env with real values.</p><p>Required minimum:</p><ul><li>AWS_PROFILE</li><li>DATA_BUCKET</li><li>ARTIFACT_BUCKET</li><li>GLUE_DATABASE</li><li>ICEBERG_WAREHOUSE=s3://&lt;DATA_BUCKET&gt;/iceberg/</li><li>ALERT_SNS_TOPIC_ARN</li></ul><p>Snowflake values:</p><ul><li>SNOWFLAKE_ACCOUNT</li><li>SNOWFLAKE_USER</li><li>SNOWFLAKE_PASSWORD</li><li>SNOWFLAKE_WAREHOUSE</li><li>SNOWFLAKE_DATABASE</li><li>SNOWFLAKE_SCHEMA</li><li>SNOWFLAKE_ROLE</li><li>SNOWFLAKE_LOAD_SQL=snowflake/03_copy_and_views.sql</li></ul><blockquote>Important: do not commit real secrets to git.</blockquote><h3>Step 4: Create a virtual environment and install dependencies</h3><ul><li>requirements.txt</li></ul><pre>boto3&gt;=1.34,&lt;2<br>botocore[crt]&gt;=1.34,&lt;2<br>pandas&gt;=2.2,&lt;3<br>pyarrow&gt;=18,&lt;20<br>pyyaml&gt;=6.0,&lt;7<br>python-dotenv&gt;=1.0,&lt;2<br>requests&gt;=2.32,&lt;3<br>snowflake-connector-python&gt;=3.11,&lt;4<br>PyNaCl&lt;1.6<br>tenacity&gt;=9,&lt;10<br>pytest&gt;=8.0,&lt;9<br>moto[s3]&gt;=5.0,&lt;6</pre><ul><li>airflow/requirements.txt</li></ul><pre>apache-airflow==2.10.5<br>PyNaCl&lt;1.6</pre><pre>cd /home/Projects/healthcare-rcm-platform<br>python3 -m venv .venv<br>. .venv/bin/activate<br><br>pip install -r requirements.txt<br>pip install -r airflow/requirements.txt<br><br>mkdir -p data/public_raw data/public_seed data/vendor_feeds data/.ivy2 .airflow</pre><blockquote>Note: PyNaCl&lt;1.6 and Snowflake connector versions are pinned to avoid dependency conflicts.</blockquote><h3>Step 5: Ensure Docker is running (Spark jobs depend on it)</h3><ul><li>docker-compose.yml</li></ul><pre>services:<br>  spark:<br>    profiles: [&quot;spark&quot;]<br>    build:<br>      context: .<br>      dockerfile: docker/spark.Dockerfile<br>    working_dir: /workspace<br>    volumes:<br>      - ./:/workspace<br>      - ${HOME}/.aws:/root/.aws:ro<br>      - ./data/.ivy2:/root/.ivy2<br>    environment:<br>      AWS_REGION: ${AWS_REGION:-us-east-1}<br>      AWS_DEFAULT_REGION: ${AWS_DEFAULT_REGION:-us-east-1}<br>      AWS_PROFILE: ${AWS_PROFILE:-default}<br>      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID:-}<br>      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY:-}<br>      AWS_SESSION_TOKEN: ${AWS_SESSION_TOKEN:-}<br>    cpus: ${SPARK_CONTAINER_CPUS:-2.0}<br>    mem_limit: ${SPARK_CONTAINER_MEM_LIMIT:-6g}<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;python&quot;, &quot;-c&quot;, &quot;import pyspark; print(&#39;ok&#39;)&quot;]<br>      interval: 30s<br>      timeout: 10s<br>      retries: 3<br>      start_period: 20s</pre><pre>sudo systemctl enable --now docker<br>docker --version<br>docker compose version</pre><h3>Step 6: Manual Snowflake + AWS stage integration setup (required once)</h3><p>This is the most important one-time setup for the mandatory Snowflake load task.</p><h4>9.1 Run security and warehouse SQL</h4><p>In the Snowflake worksheet, as ACCOUNTADMIN, run:</p><ul><li>snowflake/01_security_and_warehouse.sql</li></ul><p>Before running, update user grants if needed.</p><h4>9.2 Create AWS IAM role for Snowflake S3 stage access</h4><pre># Project root<br><br>export ROLE_NAME=hc-rcm-snowflake-stage-role<br><br>cat &gt;/tmp/sf-trust-bootstrap.json &lt;&lt;EOF2<br>{<br>  &quot;Version&quot;:&quot;2012-10-17&quot;,<br>  &quot;Statement&quot;:[<br>    {<br>      &quot;Effect&quot;:&quot;Allow&quot;,<br>      &quot;Principal&quot;:{&quot;AWS&quot;:&quot;arn:aws:iam::${AWS_ACCOUNT_ID}:root&quot;},<br>      &quot;Action&quot;:&quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}<br>EOF2<br><br>aws iam create-role \<br>  --role-name &quot;$ROLE_NAME&quot; \<br>  --assume-role-policy-document file:///tmp/sf-trust-bootstrap.json \<br>  --profile &quot;$AWS_PROFILE&quot; || true<br><br>cat &gt;/tmp/sf-s3-policy.json &lt;&lt;EOF2<br>{<br>  &quot;Version&quot;:&quot;2012-10-17&quot;,<br>  &quot;Statement&quot;:[<br>    {<br>      &quot;Effect&quot;:&quot;Allow&quot;,<br>      &quot;Action&quot;:[&quot;s3:ListBucket&quot;],<br>      &quot;Resource&quot;:[&quot;arn:aws:s3:::${DATA_BUCKET}&quot;]<br>    },<br>    {<br>      &quot;Effect&quot;:&quot;Allow&quot;,<br>      &quot;Action&quot;:[&quot;s3:GetObject&quot;],<br>      &quot;Resource&quot;:[&quot;arn:aws:s3:::${DATA_BUCKET}/snowflake_exports/*&quot;]<br>    }<br>  ]<br>}<br>EOF2<br><br>aws iam put-role-policy \<br>  --role-name &quot;$ROLE_NAME&quot; \<br>  --policy-name SnowflakeS3Read \<br>  --policy-document file:///tmp/sf-s3-policy.json \<br>  --profile &quot;$AWS_PROFILE&quot;</pre><h4>9.3 Configure Snowflake stage and curated tables</h4><p>Open snowflake/02_stages_and_tables.sql and verify values are correct for your environment:</p><ul><li>STORAGE_AWS_ROLE_ARN</li><li>S3 bucket path in STORAGE_ALLOWED_LOCATIONS</li><li>stage URL</li></ul><p>Run it in Snowflake as ACCOUNTADMIN.</p><p>Then run:</p><pre>DESC INTEGRATION HC_RCM_S3_INT;</pre><p>Copy these outputs:</p><ul><li>STORAGE_AWS_IAM_USER_ARN</li><li>STORAGE_AWS_EXTERNAL_ID</li></ul><h4>9.4 Update IAM trust policy with Snowflake principal + external ID</h4><pre># Project root<br><br>SF_IAM_USER_ARN=&quot;&lt;STORAGE_AWS_IAM_USER_ARN_FROM_DESC&gt;&quot;<br>SF_EXTERNAL_ID=&quot;&lt;STORAGE_AWS_EXTERNAL_ID_FROM_DESC&gt;&quot;<br><br>cat &gt;/tmp/sf-trust-final.json &lt;&lt;EOF2<br>{<br>  &quot;Version&quot;:&quot;2012-10-17&quot;,<br>  &quot;Statement&quot;:[<br>    {<br>      &quot;Effect&quot;:&quot;Allow&quot;,<br>      &quot;Principal&quot;:{&quot;AWS&quot;:&quot;${SF_IAM_USER_ARN}&quot;},<br>      &quot;Action&quot;:&quot;sts:AssumeRole&quot;,<br>      &quot;Condition&quot;:{&quot;StringEquals&quot;:{&quot;sts:ExternalId&quot;:&quot;${SF_EXTERNAL_ID}&quot;}}<br>    }<br>  ]<br>}<br>EOF2<br><br>aws iam update-assume-role-policy \<br>  --role-name &quot;$ROLE_NAME&quot; \<br>  --policy-document file:///tmp/sf-trust-final.json \<br>  --profile &quot;$AWS_PROFILE&quot;</pre><blockquote>If this is skipped or wrong, the Airflow task load_gold_to_snowflake will fail with: Integration &#39;HC_RCM_S3_INT&#39; does not exist or not authorized</blockquote><h3>Step 7: Initialize Airflow locally</h3><pre>cd /home/Projects/healthcare-rcm-platform<br>. .venv/bin/activate<br>set -a; source .env; set +a<br>export AIRFLOW_HOME=&quot;$(pwd)/.airflow&quot;<br><br>airflow db migrate<br>airflow users create \<br>  --username admin \<br>  --firstname admin \<br>  --lastname user \<br>  --role Admin \<br>  --email admin@example.com \<br>  --password admin</pre><h3>Step 8: Start Airflow services (two terminals)</h3><h4>Terminal A:</h4><pre>cd /home/Projects/healthcare-rcm-platform<br>. .venv/bin/activate<br>set -a; source .env; set +a<br>export AIRFLOW_HOME=&quot;$(pwd)/.airflow&quot;<br>airflow webserver --port 8080</pre><h4>Terminal B:</h4><pre>cd /home/Projects/healthcare-rcm-platform<br>. .venv/bin/activate<br>set -a; source .env; set +a<br>export AIRFLOW_HOME=&quot;$(pwd)/.airflow&quot;<br>airflow scheduler</pre><p>Open UI at <a href="http://localhost:8080.">http://localhost:8080</a>. Trigger the DAG!</p><h3>Step 9: Validate outputs</h3><h4>#1 Validate S3 landing paths</h4><pre># Project CLI<br><br>aws s3 ls &quot;s3://${DATA_BUCKET}/bronze/&quot; --recursive | head<br>aws s3 ls &quot;s3://${DATA_BUCKET}/iceberg/&quot; --recursive | head<br>aws s3 ls &quot;s3://${DATA_BUCKET}/snowflake_exports/${RUN_DATE_UTC}/&quot; --recursive</pre><h4>#2 Validate Snowflake load</h4><pre>-- Snowflake worksheet<br><br>SELECT run_date, COUNT(*)<br>FROM HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY<br>GROUP BY 1<br>ORDER BY 1 DESC;<br><br>SELECT run_date, COUNT(*)<br>FROM HC_RCM.CURATED.FINANCE_REPORTING_DAILY<br>GROUP BY 1<br>ORDER BY 1 DESC;<br><br>SELECT *<br>FROM HC_RCM.CURATED.VW_EXECUTIVE_DAILY<br>ORDER BY metric_date DESC<br>LIMIT 20;</pre><h3>KPI tables and business value</h3><ul><li>revenue_cycle_kpi_daily: tells you if each facility gets paid well and where denials hurt.</li><li>finance_reporting_daily: daily money summary of billed, expected, paid, and adjustments.</li><li>denial_trends_daily: shows denial reasons getting worse so teams can fix root causes.</li><li>reimbursement_lag_daily: tracks payment delays that impact cash flow.</li><li>facility_operational_efficiency_daily: finds workflow bottlenecks and rework hotspots.</li><li>patient_access_growth_daily: tracks referral-to-visit conversion and scheduling speed.</li><li>compliance_monitor_daily: monitors data-quality risk so dashboards stay trustworthy.</li></ul><h3>Recommended Snowflake KPI queries for leadership</h3><p>In the Snowflake worksheet</p><pre>-- Executive daily scorecard: quick health snapshot by day<br>SELECT<br>  metric_date,<br>  COUNT(DISTINCT facility_id) AS facilities_reporting,<br>  SUM(claim_count) AS total_claims,<br>  AVG(denial_rate) AS avg_denial_rate,<br>  AVG(avg_reimbursement_lag_days) AS avg_reimbursement_lag_days,<br>  AVG(net_collection_ratio_proxy) AS avg_net_collection_ratio<br>FROM HC_RCM.CURATED.VW_EXECUTIVE_DAILY<br>GROUP BY metric_date<br>ORDER BY metric_date DESC<br>LIMIT 30;<br><br><br>-- Top revenue opportunity: where expected revenue is high but paid is lower<br>SELECT<br>  run_date,<br>  facility_id,<br>  facility_name,<br>  SUM(total_expected_allowed_amount) AS expected_revenue,<br>  SUM(total_paid_amount) AS paid_revenue,<br>  SUM(total_expected_allowed_amount) - SUM(total_paid_amount) AS revenue_gap<br>FROM HC_RCM.CURATED.FINANCE_REPORTING_DAILY<br>GROUP BY run_date, facility_id, facility_name<br>ORDER BY run_date DESC, expected_revenue DESC<br>LIMIT 10;<br><br><br>-- Worst denial rates at meaningful volume<br>SELECT<br>  run_date,<br>  facility_id,<br>  facility_name,<br>  SUM(claim_count) AS total_claims,<br>  SUM(denied_claims) AS total_denied,<br>  SUM(denied_claims) / NULLIF(SUM(claim_count), 0) AS denial_rate<br>FROM HC_RCM.CURATED.REVENUE_CYCLE_KPI_DAILY<br>GROUP BY run_date, facility_id, facility_name<br>HAVING SUM(claim_count) &gt;= 100<br>ORDER BY run_date DESC, denial_rate DESC<br>LIMIT 15;<br><br><br>-- Reimbursement lag leaderboard: slowest facilities first<br>SELECT<br>  run_date,<br>  facility_id,<br>  facility_name,<br>  AVG(avg_reimbursement_lag_days) AS avg_lag_days,<br>  AVG(p95_reimbursement_lag_days) AS p95_lag_days<br>FROM HC_RCM.CURATED.REIMBURSEMENT_LAG_DAILY<br>GROUP BY run_date, facility_id, facility_name<br>ORDER BY run_date DESC, avg_lag_days DESC<br>LIMIT 15;<br><br><br>-- Operational bottlenecks by workflow stage<br>SELECT<br>  run_date,<br>  bottleneck_stage,<br>  SUM(claims_touched) AS claims_touched,<br>  AVG(avg_touch_count) AS avg_touch_count,<br>  AVG(rework_rate) AS avg_rework_rate<br>FROM HC_RCM.CURATED.FACILITY_OPERATIONAL_EFFICIENCY_DAILY<br>GROUP BY run_date, bottleneck_stage<br>ORDER BY run_date DESC, claims_touched DESC;</pre><h3>Common failure modes</h3><h4>#1 Integration &#39;HC_RCM_S3_INT&#39; does not exist or not authorized</h4><p>Cause: Storage integration missing, wrong role ARN, or IAM trust policy not updated with Snowflake external ID.</p><p>Fix:</p><ul><li>Re-run snowflake/02_stages_and_tables.sql.</li><li>Run DESC INTEGRATION HC_RCM_S3_INT.</li><li>Update IAM trust with STORAGE_AWS_IAM_USER_ARN + STORAGE_AWS_EXTERNAL_ID.</li></ul><h4>#2 Iceberg stale metadata error (Location does not exist, NoSuchKeyException)</h4><p>Cause: Glue table points to missing Iceberg metadata JSON.</p><p>Fix: Current Spark jobs already self-heal this in replace_table() by deleting stale Glue table metadata and retrying.</p><h4>#3 S3 400 Bad Request during Spark parquet commit</h4><p>Cause: S3A commit edge cases for direct output path handling.</p><p>Fix: silver_to_gold.py writes export locally (coalesce(1)) then uploads the file using boto3/AWS SDK.</p><h4>#4 Python dependency conflict (cffi, PyNaCl)</h4><p>Cause: Connector transitive dependency downgrade.</p><p>Fix: Keep PyNaCl&lt;1.6 pin as in requirements.txt and airflow/requirements.txt.</p><h3>Conclusion</h3><p>This project gives you a strong end-to-end foundation: raw data download, controlled ingestion, Silver/Gold transformations, quality checks, and mandatory Snowflake loading in one pipeline. In simple terms, it is built so that data is traceable, checks are enforced, and business teams can consume KPI tables without manual steps.</p><p>Here, the flow is idempotent, schema-aware, and observable. If a run fails, you get clear logs and alerts, and common issues like stale Iceberg metadata are already handled in code, so retries are more reliable.</p><p>To take this from a strong demo to production, focus next on platform hardening: move secrets out of .env, add CI checks for DAG/SQL, improve governance for sensitive fields, and add recovery/runbook coverage. With those upgrades, this design can scale into a serious healthcare analytics platform. Happy Coding! 🚀🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gvk31UkbzaCW3mRnPqJDSA.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d104ec9303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hybrid AI Data Platform for Sensor and RF Pipelines]]></title>
            <link>https://medium.com/@thisis-Shitanshu/hybrid-ai-data-platform-for-sensor-and-rf-pipelines-1042a6a31398?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/1042a6a31398</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 18:35:20 GMT</pubDate>
            <atom:updated>2026-07-01T09:55:12.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>Versioned datasets, reproducible pipelines, Spark feature engineering, MLflow lifecycle, drift monitoring, and FastAPI serving on Docker; End-to-end.</h4><p>Most data teams can build individual ETL pipelines, but scaling that work across many users requires something bigger: a data platform. Data Engineering usually focuses on building specific pipelines for analytics. Data Platform Engineering focuses on building the shared, self-service foundation (storage, orchestration, observability, CI/CD, reproducibility, and secure deployment patterns) so that data engineers and data scientists can build and ship pipelines faster, with reliability.</p><p>In measurement-heavy domains (RF, sensors, time-series signals, test-and-measurement systems), the data looks very different from typical “business tables.” You deal with signal windows, noise, hardware impairments, and shifting environments. To make this practical and reproducible, this project generates a realistic synthetic dataset of baseband I/Q signal windows, along with impairment parameters like SNR, carrier frequency offset (CFO), and phase noise. On top of this dataset, we train a model to classify modulation type, then continuously monitor drift when the data distribution changes.</p><p>The goal is to build a mini internal AI platform for test-and-measurement style sensor/RF data, end-to-end:</p><ul><li>Data platform: a versioned data lake using lakeFS on S3-compatible storage (local MinIO in this article, easily switchable to AWS S3 later)</li><li>Pipelines: Airflow orchestration for ingestion → profiling and quality gates → Spark-based feature engineering → training</li><li>MLOps: MLflow for experiment tracking, model registry, and controlled promotion or rollback</li><li>Monitoring: drift detection with Evidently, metrics scraped by Prometheus, and dashboards in Grafana</li><li>Developer enablement: a FastAPI service for prediction and data access, plus a small Python SDK for clean consumption</li><li>Our Hybrid story: everything runs locally using Docker Compose for an on-prem style setup; the same architecture can be migrated to AWS with minimal changes because the storage layer is S3-compatible, and the infrastructure can be provisioned with Terraform (AWS provisioning is out of scope for this article, but the design keeps migration straightforward)</li></ul><p>By the end, you will have a working local platform with these UIs and endpoints:</p><ul><li>Airflow UI: <a href="http://localhost:8080/">http://localhost:8080</a></li><li>lakeFS UI: <a href="http://localhost:8000/">http://localhost:8000</a></li><li>MLflow UI: <a href="http://localhost:5000/">http://localhost:5000</a></li><li>FastAPI docs: <a href="http://localhost:9000/docs">http://localhost:9000/docs</a></li><li>Prometheus: <a href="http://localhost:9090/">http://localhost:9090</a></li><li>Grafana: <a href="http://localhost:3000/">http://localhost:3000</a> (admin/admin)</li></ul><p>You will also have tangible outputs:</p><ul><li>Versioned datasets in lakeFS (branches and commits)</li><li>MLflow runs and a registered model promoted to “Production”</li><li>Drift metrics visible in Prometheus and Grafana</li></ul><p>Let’s start building: hybrid-signalforge 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Erq-7ZRMLOlspk4pzSr_Q.png" /></figure><h3>System Setup</h3><h4>1. Prerequisites</h4><p>Install these on your machine:</p><ul><li>Docker Engine + Docker Compose v2</li><li>Python 3.11+</li><li>Make (optional, but convenient)</li></ul><h4>2. Folder structure</h4><p>We will work with the following structure:</p><pre>HYBRID-SIGNALFORGE/<br>├── airflow/<br>│   └── dags/<br>│       └── signalforge_pipeline.py<br>├── api/<br>│   ├── Dockerfile<br>│   └── app.py<br>├── docker/<br>│   ├── airflow/<br>│   │   └── Dockerfile<br>│   ├── grafana/<br>│   │   ├── dashboards/<br>│   │   └── provisioning/<br>│   │       ├── dashboards/<br>│   │       │   └── dashboard.yml<br>│   │       └── datasources/<br>│   │           └── datasource.yml<br>│   ├── mlflow/<br>│   │   └── Dockerfile<br>│   ├── postgres/<br>│   │   └── init.sql<br>│   ├── prometheus/<br>│   │   └── prometheus.yml<br>│   └── spark/<br>│       └── Dockerfile<br>├── spark_jobs/<br>│   └── feature_engineering.py<br>├── src/<br>│   └── signalforge/<br>│       ├── __init__.py<br>│       ├── config.py<br>│       ├── data_gen.py<br>│       ├── drift.py<br>│       ├── feature_extract.py<br>│       ├── lakefs_bootstrap.py<br>│       ├── lakefs_ops.py<br>│       ├── quality.py<br>│       └── train.py<br>├── .env<br>├── .env.example<br>├── .gitignore<br>├── docker-compose.airflow.yml<br>├── docker-compose.base.yml<br>├── docker-compose.obs.yml<br>├── docker-compose.spark.yml<br>├── docker-compose.yml<br>├── README.md<br>├── requirements.airflow.txt<br>├── requirements.api.txt<br>├── requirements.mlflow.txt<br>└── requirements.spark.txt</pre><h4>3. Installation commands</h4><p>From inside hybrid-signalforge/:</p><pre>cp .env.example .env<br>docker compose up -d --build</pre><blockquote>Note: Environment variables, we already copied .env.example → .env. Defaults are local-safe.</blockquote><h4>4. How to run the project</h4><p>After everything is complete:</p><pre>make bootstrap<br>make trigger</pre><h4>Final Verification</h4><ul><li>Airflow UI: Admin/admin login will be created during init</li><li>DAG name: signalforge_end_to_end should run and succeed</li></ul><h3>Step 0: Create our central config for all services.</h3><pre>cat &gt; .env.example &lt;&lt; &#39;EOF&#39;<br># ---------- Common ----------<br>PROJECT_NAME=hybrid-signalforge<br><br># ---------- Postgres ----------<br>POSTGRES_HOST=postgres<br>POSTGRES_PORT=5432<br>POSTGRES_SUPERUSER=postgres<br>POSTGRES_SUPERPASS=postgres<br><br># Airflow DB<br>AIRFLOW_DB=airflow<br>AIRFLOW_DB_USER=airflow<br>AIRFLOW_DB_PASS=airflow<br><br># lakeFS DB<br>LAKEFS_DB=lakefs<br>LAKEFS_DB_USER=lakefs<br>LAKEFS_DB_PASS=lakefs<br><br># MLflow DB<br>MLFLOW_DB=mlflow<br>MLFLOW_DB_USER=mlflow<br>MLFLOW_DB_PASS=mlflow<br><br># ---------- MinIO ----------<br>MINIO_ROOT_USER=minioadmin<br>MINIO_ROOT_PASSWORD=minioadmin<br>MINIO_ENDPOINT_INTERNAL=http://minio:9000<br>MINIO_ENDPOINT_EXTERNAL=http://localhost:9001<br><br># ---------- lakeFS (server) ----------<br>LAKEFS_ENDPOINT_INTERNAL=http://lakefs:8000<br>LAKEFS_ENDPOINT_EXTERNAL=http://localhost:8000<br>LAKEFS_AUTH_ENCRYPT_SECRET_KEY=dev-secret-key-change-in-prod<br><br># lakeFS first-user bootstrap credentials (used once)<br>LAKEFS_BOOTSTRAP_USERNAME=admin<br>LAKEFS_BOOTSTRAP_ACCESS_KEY_ID=AKIASIGNALFORGE00001<br>LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY=signalforgeSecretKeyLocalMinio0000000000<br><br># Repository used by the project<br>LAKEFS_REPO=signalforge<br><br># ---------- MLflow ----------<br>MLFLOW_TRACKING_URI=http://mlflow:5000<br>MLFLOW_ARTIFACT_BUCKET=mlflow<br><br># ---------- SignalForge pipeline ----------<br>SIGNALFORGE_N_SAMPLES=3000<br>SIGNALFORGE_WINDOW=1024<br>SIGNALFORGE_DRIFT_THRESHOLD=0.6<br><br># ---------- FastAPI ----------<br>API_PORT=9000<br><br># ---------- Airflow ----------<br>AIRFLOW_UID=50000<br>AIRFLOW_WWW_USER_USERNAME=admin<br>AIRFLOW_WWW_USER_PASSWORD=admin<br>AIRFLOW_API_SECRET_KEY=signalforge-api-secret<br>AIRFLOW_WEBSERVER_SECRET_KEY=signalforge-webserver-secret<br>AIRFLOW_API_AUTH_JWT_SECRET=signalforge-api-jwt-secret<br>AIRFLOW__WEBSERVER__BASE_URL=http://localhost:8080<br>EOF</pre><p>Copy it to .env from the project root:</p><pre>cp .env.example .env</pre><h3>Pause: Understand the tools and platform components</h3><p>I find it easier to work with complex systems when I treat each version of a component as a “personality” with a clear responsibility, behavior, and failure mode. Spending a few minutes to understand what each service needs and how it talks to others saves hours of debugging later. Below is a deeper, practical introduction to the components in this project and the key Docker Compose considerations you should keep in mind while running everything locally.</p><h4>1. Docker and Docker Compose</h4><p>Docker Compose runs multiple containers on a shared network with shared volumes. The biggest things to get right are networking (service DNS names inside Compose vs host ports on localhost), persistent volumes (so metadata and artifacts survive restarts), and resource limits (so one container does not starve others). Common issues are port conflicts (for example, 9000), services accidentally isolated on different networks, and wrong URLs because host and container networking were mixed up.</p><h4>2. PostgreSQL</h4><p>Postgres stores metadata for Airflow and MLflow. Important considerations are keeping one consistent set of credentials (single source of truth), using health checks so dependent services wait until Postgres is ready, and avoiding I/O starvation that can cause Airflow scheduler lag. Common failures include schema mismatches after upgrades, permission issues from wrong DB or user, and connection refused during startup because services try to connect too early.</p><h4>3. MinIO</h4><p>MinIO provides S3-compatible object storage for the platform. Key considerations are using one consistent endpoint and credentials across all services, ensuring buckets are created before anything tries to write artifacts, and understanding the port split (API vs console). Common failures include using the wrong endpoint (confusing 9000 and 9001), missing buckets, and client mismatches around path-style access or region assumptions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLFOIsHSSYIK37B3VtACkNksUw8_puUuAC&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLFOIsHSSYIK37B3VtACkNksUw8_puUuAC&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgY090GEDdu8%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLBqShW3fRcQ6No1aqIkh2dKoiRWgQ%26days_since_epoch%3D20594&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5651b84987efecb52037c47aa56c0f/href">https://medium.com/media/2a5651b84987efecb52037c47aa56c0f/href</a></iframe><blockquote>Recommended Watch: <a href="https://www.youtube.com/playlist?list=PLFOIsHSSYIK3h-ckBmtbFEtxNajnA5Txu">Installing and Running MinIO on Docker</a></blockquote><h4>4. lakeFS</h4><p>lakeFS adds Git-like versioning on top of object storage. Design-wise, it needs a reliable Postgres connection for metadata, correct S3 endpoint configuration to talk to MinIO, and an automated bootstrap for initial admin setup and repository creation. Common failures include lakeFS starting before Postgres is healthy, repositories not initialized, and invalid branch names that break API calls.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLFa0Xeb5b5qwf7W29xSktYDsP49w8cBlJ&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLFa0Xeb5b5qwf7W29xSktYDsP49w8cBlJ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5lAVPzoWmoI%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLBU-jHL8JKl4olGfMxxhcWcLgGH9Q%26days_since_epoch%3D20471&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4bfbe1c93e5c2ca00fde0be2eac5ed0/href">https://medium.com/media/d4bfbe1c93e5c2ca00fde0be2eac5ed0/href</a></iframe><blockquote>Recommended Watch: <a href="https://www.youtube.com/playlist?list=PLFa0Xeb5b5qzfxGDzwm_wl0U0OzR1J54v">Getting started with lakeFS data version</a></blockquote><h4>5. Airflow</h4><p>Airflow orchestrates the end-to-end pipeline. In local development, the most important choices are stable entrypoints and health checks, consistent secrets and auth configuration between scheduler and webserver, and conservative parallelism so Postgres is not overloaded. Common failures include scheduler/webserver mismatches, invalid auth tokens, and slow task instance creation when the metadata database becomes a bottleneck.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLGudixcDaxY3A4P-wmH1wBHqLUU6c1DOU&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLGudixcDaxY3A4P-wmH1wBHqLUU6c1DOU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_QZFgQcGPYA%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLCwpYjO5M85S09yUR1hkLX8z_6XVA%26days_since_epoch%3D20471&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1ca7af9861f80cc285c0f673e6d2a39/href">https://medium.com/media/c1ca7af9861f80cc285c0f673e6d2a39/href</a></iframe><h4>6. Spark</h4><p>Spark handles feature engineering and larger-scale transformations. You need correct container roles (master/worker), controlled resources (cores, memory, partitions), so local machines do not get overwhelmed, and correct dependency management for S3 access (for example, hadoop-aws jars). Common failures include spark-submit not being available in PATH, schema mismatches in pandas UDFs, and runaway memory or CPU usage that makes the whole stack unstable.</p><h4>7. MLflow</h4><p>MLflow provides experiment tracking and the model registry. The main considerations are keeping client and server versions compatible, ensuring database schema initialization and upgrades are handled correctly, and confirming artifact access works through the S3-compatible layer. Common failures include out-of-date database schemas, broken endpoints due to version mismatch, and missing artifacts because the S3 endpoint or credentials were wrong.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLTPXxbhUt-YWjDg318nmSxRqTgZFWQ2ZC&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLTPXxbhUt-YWjDg318nmSxRqTgZFWQ2ZC&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fx3cxvsUFVZA%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLDjmx4A6n6M1Pm13TdHMaduneYiOg%26days_since_epoch%3D20471&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2812b899d19e15a627f1ca54ce362979/href">https://medium.com/media/2812b899d19e15a627f1ca54ce362979/href</a></iframe><h4>8. FastAPI</h4><p>FastAPI is the serving layer for predictions (and metrics exposure where needed). It must load the model from the MLflow registry, access artifacts through S3-compatible storage if required, and behave predictably when the “Production” model is not yet available. Common failures include API startup crashing because a model is missing, and networking issues where the container cannot reach MLflow.</p><h4>9. Prometheus</h4><p>Prometheus scrapes metrics from services (API and Pushgateway). The key is correct scrape target configuration using container DNS names and ensuring the targets are actually healthy. Common failures are unreachable scrape endpoints due to the wrong service name or port.</p><h4>10. Grafana</h4><p>Grafana visualizes Prometheus data. You need correct provisioning configuration, a persistent volume for dashboards and state, and a correct Prometheus datasource URL from inside the container network. Common failures include pointing the datasource to localhost (host) instead of the Prometheus service (container network), and provisioning files not mounted at the expected path.</p><h4>11. Pushgateway</h4><p>Pushgateway receives batch metrics (for example, drift outputs). It needs stable job naming and a reachable endpoint for batch jobs. Common failures are drift tasks pushing when Pushgateway is not running, or Prometheus scraping the wrong endpoint.</p><h4>Operational rules to follow in a multi-service stack</h4><p>When you run an “orchestra” of components like this, these checks prevent most failures:</p><ul><li>Separate host access from service-to-service access: inside Compose use service DNS names (mlflow, spark-master); from your laptop use localhost plus the published port.</li><li>Pin versions for API-driven components (Airflow, MLflow, lakeFS, Spark). Avoid “latest” for core infra.</li><li>After any major version bump, re-check the startup command and health endpoints, and confirm your health checks match reality.</li><li>Initialize database schemas correctly before upgrades. Some tools require an explicit “init schema then upgrade” flow.</li><li>Keep resource usage conservative in local dev: cap CPU, memory, worker cores, and Airflow parallelism.</li><li>Standardize S3 endpoint, credentials, and client behavior across all components.</li><li>Follow naming rules strictly (buckets, repos, branches, registered model names) because APIs often reject invalid names.</li><li>Ensure dependencies are healthy before starting dependents (and add retries/backoff in pipelines).</li><li>Test connectivity from both angles: from the host (localhost) and from inside the network (service DNS).</li><li>Persist logs and state to volumes you can easily inspect.</li><li>Keep a single source of truth for configuration via .env.</li><li>Prefer idempotent bootstrap steps that are safe to run again.</li></ul><h3>Step 1: Python dependencies</h3><p>Goal: keep dependencies consistent and predictable across the whole stack (Airflow tasks, Spark jobs where relevant, and the FastAPI service).</p><p>In this project, the main Python libraries and why we need them are:</p><h4>S3-compatible storage clients (MinIO today, AWS S3 later)</h4><ul><li>boto3 and botocore: used to talk to S3-compatible object storage. In this project, we use MinIO (S3-compatible), and the same client layer can later point to AWS S3 by changing endpoints and credentials.</li></ul><h4>Data processing and feature engineering</h4><ul><li>pandas: tabular data manipulation and pipeline-friendly transforms.</li><li>numpy: efficient numerical arrays for signal windows and feature computations.</li><li>pyarrow: efficient columnar memory format used for Parquet and fast IO.</li><li>scipy: scientific routines (statistics, signal-related utilities, and numeric helpers).</li></ul><h4>Machine learning and model lifecycle</h4><ul><li>scikit-learn: baseline ML training and evaluation for classification.</li><li>mlflow: experiment tracking and model registry (promotions like Staging/Production).</li></ul><h4>Databases and service communication</h4><ul><li>psycopg2-binary: Postgres adapter for Airflow and MLflow metadata interactions.</li><li>requests: simple HTTP calls between services (for example, calling MLflow, lakeFS, or internal APIs).</li></ul><h4>API layer</h4><ul><li>fastapi: the prediction and data-access service.</li><li>pydantic: request/response validation and typed configs.</li><li>uvicorn: ASGI server to run the FastAPI app.</li></ul><h4>Monitoring and data quality</h4><ul><li>prometheus-client: exposes metrics from Python services for Prometheus scraping.</li><li>evidently: drift detection and monitoring reports/metrics for changing data distributions.</li><li>pandera: validation rules for pandas DataFrames (quality gates).</li></ul><h4>Platform integration utilities</h4><ul><li>lakefs-client: Python client for interacting with lakeFS (repos, branches, commits, and object operations).</li><li>python-dotenv: loads environment variables from .env for consistent configuration across services.</li></ul><blockquote>Dependency isolation strategy: Instead of a single requirements.txt for everything, we will maintain separate dependency files per service (for example, requirements.airflow.txt, requirements.api.txt, requirements.mlflow.txt, requirements.spark.txt). This reduces version conflicts and makes builds reproducible because each container installs only what it actually needs.</blockquote><pre>cat &gt; requirements.airflow.txt &lt;&lt; &#39;EOF&#39;<br>apache-airflow-providers-docker<br>apache-airflow-providers-fab<br><br>boto3<br>botocore<br><br>pandas<br>numpy==1.26.4<br>pyarrow<br>scipy<br>scikit-learn<br><br>mlflow==3.2.0<br>psycopg2-binary<br>requests<br><br>evidently==0.4.33<br>pandera==0.20.3<br>lakefs-client==1.44.0<br>python-dotenv<br>EOF</pre><pre>cat &gt; requirements.api.txt &lt;&lt; &#39;EOF&#39;<br>boto3==1.34.162<br>botocore==1.34.162<br>pandas==2.2.2<br>numpy==1.26.4<br>pyarrow==15.0.2<br>scipy==1.14.0<br>scikit-learn==1.5.1<br>mlflow==3.2.0<br>psycopg2-binary==2.9.9<br>requests==2.32.3<br>pydantic==2.8.2<br>fastapi==0.112.0<br>uvicorn==0.30.6<br>prometheus-client==0.20.0<br>evidently==0.4.33<br>pandera==0.20.3<br>lakefs-client==1.44.0<br>python-dotenv==1.0.1<br>EOF</pre><pre>cat &gt; requirements.mlflow.txt &lt;&lt; &#39;EOF&#39;<br>mlflow==3.2.0<br>psycopg2-binary==2.9.9<br>boto3==1.34.162<br>botocore==1.34.162<br>requests==2.32.3<br>EOF</pre><pre>cat &gt; requirements.spark.txt &lt;&lt; &#39;EOF&#39;<br>numpy==1.24.4<br>pandas==1.5.3<br>pyarrow==12.0.1<br>scipy==1.10.1<br>EOF</pre><h3>Step 2: Postgres init script</h3><p>Goal: create separate databases and users for Airflow, lakeFS, and MLflow.</p><p>We intentionally provision separate Postgres databases and users for each service because they store different kinds of metadata and have different access patterns. This isolation prevents accidental interference, improves security, and makes failures easier to diagnose.</p><h4>What each service stores in Postgres</h4><ul><li>Airflow: scheduler state, DAG runs, task instances, and connection/variable metadata used to run pipelines reliably.</li><li>lakeFS: repository metadata such as branches, commits, and object versioning pointers (the data itself stays in object storage, but lakeFS needs Postgres for its control plane).</li><li>MLflow: experiment runs, parameters, metrics, artifacts metadata, and model registry records.</li></ul><h4>Why not share a single database/user</h4><p>If all services shared one database or one Postgres user, a misconfiguration, a heavy workload spike, or a schema change from one service could impact the others. That creates unpredictable performance and increases the chance of “one component breaking everything.”</p><blockquote>(Security and production readiness) Separate databases and users also enforce least-privilege access: each service only has permissions on its own database. This is closer to real production practice and makes it safer to later migrate to managed Postgres or tighter compliance setups without redesigning your metadata layer.</blockquote><pre>mkdir -p docker/postgres<br><br>cat &gt; docker/postgres/init.sql &lt;&lt; &#39;EOF&#39;<br>-- Airflow DB + user<br>CREATE DATABASE airflow;<br>CREATE USER airflow WITH ENCRYPTED PASSWORD &#39;airflow&#39;;<br>GRANT ALL PRIVILEGES ON DATABASE airflow TO airflow;<br>\connect airflow;<br>GRANT ALL ON SCHEMA public TO airflow;<br>ALTER SCHEMA public OWNER TO airflow;<br><br>-- lakeFS DB + user<br>CREATE DATABASE lakefs;<br>CREATE USER lakefs WITH ENCRYPTED PASSWORD &#39;lakefs&#39;;<br>GRANT ALL PRIVILEGES ON DATABASE lakefs TO lakefs;<br>\connect lakefs;<br>GRANT ALL ON SCHEMA public TO lakefs;<br>ALTER SCHEMA public OWNER TO lakefs;<br><br>-- MLflow DB + user<br>CREATE DATABASE mlflow;<br>CREATE USER mlflow WITH ENCRYPTED PASSWORD &#39;mlflow&#39;;<br>GRANT ALL PRIVILEGES ON DATABASE mlflow TO mlflow;<br>\connect mlflow;<br>GRANT ALL ON SCHEMA public TO mlflow;<br>ALTER SCHEMA public OWNER TO mlflow;<br>EOF</pre><h3>Step 3: Build a “ready” Airflow image</h3><p>Next, we build a custom Airflow Docker image that already includes our project’s Python libraries and the required Airflow providers. This matters because Airflow executes your DAG code and tasks inside the Airflow container environment. If the scheduler and webserver do not have the same dependencies as your pipeline code, tasks will fail at runtime with missing imports, incompatible versions, or provider-related errors.</p><p>What is happening in this Airflow image build (high level):</p><ul><li>We start from an official Apache Airflow base image pinned to a specific Airflow and Python version, so the runtime is predictable.</li><li>We temporarily switch to a privileged user to install a few system-level build tools (compilers and utilities) that some Python packages need during installation, then switch back to the safer non-root Airflow user.</li><li>We copy a dedicated requirements file for Airflow into the image, so only Airflow-specific dependencies are installed here.</li><li>We install Python dependencies using Airflow’s “constraints” file for the exact Airflow and Python version. This is important because constraints lock compatible dependency versions and prevent pip from upgrading or downgrading core libraries in a way that can break Airflow’s UI, scheduler, or internal APIs.</li></ul><pre>mkdir -p docker/airflow<br><br>cat &gt; docker/airflow/Dockerfile &lt;&lt; &#39;EOF&#39;<br>FROM apache/airflow:3.1.6-python3.11<br><br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \<br>    gcc g++ curl \<br>    &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/*<br>USER airflow<br><br># Airflow constraints URL keeps Airflow&#39;s dependency set consistent.<br>ARG AIRFLOW_VERSION=3.1.6<br>ARG PYTHON_VERSION=3.11<br>ARG CONSTRAINT_URL=&quot;https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt&quot;<br><br>COPY requirements.airflow.txt /requirements.airflow.txt<br><br># Install all extra deps under Airflow constraints.<br># Key point: constraints prevent pip from upgrading/downgrading core web dependencies in a way that breaks Airflow.<br>RUN pip install --no-cache-dir --constraint &quot;${CONSTRAINT_URL}&quot; -r /requirements.airflow.txt<br>EOF</pre><p>The result is an Airflow container that is “task-ready”: it can import the pipeline code, run operators/hooks/providers reliably, and stay stable across restarts and rebuilds.</p><h3>Step 4: Set up the monitoring plumbing</h3><p>Next, we wire up the observability layer: Prometheus for metric collection and Grafana for visualization. The idea is simple. Our FastAPI service exposes real-time application metrics (latency, request counts, errors, and custom model metrics), and our batch drift checks push their results to Pushgateway. Prometheus pulls from both sources on a fixed interval, and Grafana queries Prometheus to show trends and alert-worthy signals. This gives us “platform visibility” so we can detect performance issues and model or data drift from evidence, not guesswork.</p><p>What’s happening at a high level:</p><h4>1) Prometheus configuration</h4><ul><li>We define a global scrape interval so Prometheus knows how frequently to collect metrics.</li><li>We add a scrape job for the FastAPI service, pointing to its /metrics endpoint using the Docker Compose service name (api) and the container port.</li><li>We add a second scrape job for Pushgateway, so drift metrics produced by batch jobs become visible in the same metrics store.</li></ul><pre>mkdir -p docker/prometheus<br><br>cat &gt; docker/prometheus/prometheus.yml &lt;&lt; &#39;EOF&#39;<br>global:<br>  scrape_interval: 10s<br><br>scrape_configs:<br>  - job_name: &quot;fastapi&quot;<br>    metrics_path: /metrics<br>    static_configs:<br>      - targets: [&quot;api:9000&quot;]<br><br>  - job_name: &quot;pushgateway&quot;<br>    static_configs:<br>      - targets: [&quot;pushgateway:9091&quot;]<br>EOF</pre><h4>2) Grafana provisioning</h4><ul><li>We configure Grafana to use Prometheus as its default datasource by referencing the Prometheus service on the Docker network <strong>(not localhost)</strong>.</li><li>We set up dashboard provisioning so Grafana automatically loads dashboards from a known folder inside the container. This keeps the setup reproducible across restarts and machines.</li></ul><pre>mkdir -p docker/grafana/provisioning/datasources<br>mkdir -p docker/grafana/provisioning/dashboards<br><br>cat &gt; docker/grafana/provisioning/datasources/datasource.yml &lt;&lt; &#39;EOF&#39;<br>apiVersion: 1<br>datasources:<br>  - name: Prometheus<br>    type: prometheus<br>    access: proxy<br>    url: http://prometheus:9090<br>    isDefault: true<br>EOF</pre><pre>cat &gt; docker/grafana/provisioning/dashboards/dashboard.yml &lt;&lt; &#39;EOF&#39;<br>apiVersion: 1<br>providers:<br>  - name: &quot;SignalForge&quot;<br>    type: file<br>    disableDeletion: false<br>    updateIntervalSeconds: 10<br>    options:<br>      path: /var/lib/grafana/dashboards<br>EOF</pre><h4>Dashboard approach</h4><p>We keep dashboards minimal at first and query metrics directly inside Grafana while iterating. Once the metrics stabilize, we can add a curated JSON dashboard for a polished “one screen” view later.</p><blockquote>Recommended Read: <a href="https://medium.com/@thisis-Shitanshu/sre-mini-production-stack-on-aws-f1f9d92a9326">SRE Mini Production Stack on AWS</a></blockquote><h3>Step 5: Package the FastAPI service</h3><p>Next, we package the FastAPI service as its own Docker image. This API will eventually load the “Production” model from MLflow and expose a clean prediction endpoint.</p><p>The larger purpose is important: instead of every user or team needing to understand lakeFS, MLflow, storage credentials, and pipeline wiring, we provide a simple self-serve interface that hides platform complexity behind a stable contract (HTTP endpoints).</p><p>What is happening in this API image build (high level):</p><ul><li>We start from a lightweight, pinned Python runtime image so the service behaves consistently across machines.</li><li>We install only the API-specific dependencies from a dedicated requirements file, keeping the container small and reducing version conflicts with other services.</li><li>We copy the project source code and the API entrypoint into the container so the service has access to shared utilities (config, storage helpers, feature logic) and the FastAPI app itself.</li><li>We set PYTHONPATH so the container can import the src/ package cleanly without hacks.</li><li>We expose the API port and run the service using Uvicorn, which is the standard production server for FastAPI.</li></ul><pre>mkdir -p api<br><br>cat &gt; api/Dockerfile &lt;&lt; &#39;EOF&#39;<br>FROM python:3.11-slim<br><br>WORKDIR /app<br>COPY requirements.api.txt /app/requirements.txt<br>RUN pip install --no-cache-dir -r /app/requirements.txt<br><br>COPY src /app/src<br>COPY api/app.py /app/app.py<br><br>ENV PYTHONPATH=/app/src<br>EXPOSE 9000<br><br>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;9000&quot;]<br>EOF</pre><p>The result is a portable internal service container that can be started by Docker Compose, connect to the rest of the platform on the Compose network (MLflow, lakeFS, object storage), and provide predictions through a single, simple endpoint.</p><h3>Step 6: Docker Compose (core platform)</h3><p>Goal: Set up the full platform locally: lakeFS + MinIO + Airflow + Spark + MLflow + monitoring + API.</p><p>At this point, we stitch together all the moving parts into one coherent platform. Docker Compose is our “local control plane” that brings up the services, connects them on a shared network, mounts the right volumes, and injects configuration through .env. Again, the core idea is:</p><ul><li>MinIO is our local, on-prem style object storage (S3-compatible).</li><li>lakeFS sits on top of that storage to provide dataset versioning (branches, commits).</li><li>Airflow orchestrates the pipeline end-to-end.</li><li>Spark handles distributed feature engineering.</li><li>MLflow tracks experiments and manages the model registry.</li><li>Prometheus + Grafana provide observability (API metrics and drift metrics).</li><li>FastAPI exposes a clean self-serve interface for predictions (and metrics).</li></ul><p>Because this is a multi-service system, we split Compose into multiple files so we can start the platform in layers, debug faster, and avoid running heavy components before we need them.</p><h4>1. docker-compose.base.yml (foundation)</h4><p>This file brings up the foundational services that everything else depends on:</p><ul><li>Postgres as the metadata database (used by Airflow, lakeFS, MLflow).</li><li>MinIO as object storage.</li><li>A MinIO “bootstrap” container that creates the required buckets so downstream services do not fail.</li><li>lakeFS configured to use Postgres for metadata and MinIO as its S3-compatible blockstore.</li></ul><p>We also add health checks and explicit dependencies so lakeFS does not start until Postgres is ready and buckets exist.</p><pre>cat &gt; docker-compose.yml &lt;&lt; &#39;EOF&#39;<br>services:<br>  postgres:<br>    image: postgres:16<br>    networks:<br>      - signalforge<br>    env_file:<br>      - .env<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_SUPERUSER}<br>      POSTGRES_PASSWORD: ${POSTGRES_SUPERPASS}<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - pgdata:/var/lib/postgresql/data<br>      - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U $$POSTGRES_USER -d postgres&quot;]<br>      interval: 5s<br>      timeout: 3s<br>      retries: 30<br><br>  minio:<br>    image: minio/minio:latest<br>    networks:<br>      - signalforge<br>    command: server /data --console-address &quot;:9001&quot;<br>    env_file:<br>      - .env<br>    environment:<br>      MINIO_ROOT_USER: ${MINIO_ROOT_USER}<br>      MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}<br>    ports:<br>      - &quot;9001:9001&quot;<br>    expose:<br>      - &quot;9000&quot;<br>    volumes:<br>      - miniodata:/data<br><br>  minio-mc:<br>    image: minio/mc:latest<br>    networks:<br>      - signalforge<br>    depends_on:<br>      - minio<br>    entrypoint: &gt;<br>      /bin/sh -c &quot;<br>      set -e;<br>      until (/usr/bin/mc alias set local http://minio:9000 ${MINIO_ROOT_USER} ${MINIO_ROOT_PASSWORD}); do echo &#39;waiting for minio&#39; &amp;&amp; sleep 2; done;<br>      /usr/bin/mc mb -p local/lakefs || true;<br>      /usr/bin/mc mb -p local/$${MLFLOW_ARTIFACT_BUCKET:-mlflow} || true;<br>      echo &#39;minio buckets ready&#39;;<br>      &quot;<br>    restart: &quot;no&quot;<br><br>  lakefs:<br>    image: treeverse/lakefs:latest<br>    networks:<br>      - signalforge<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>      minio-mc:<br>        condition: service_completed_successfully<br>    env_file:<br>      - .env<br>    environment:<br>      LAKEFS_DATABASE_TYPE: postgres<br>      LAKEFS_DATABASE_POSTGRES_CONNECTION_STRING: postgres://${LAKEFS_DB_USER}:${LAKEFS_DB_PASS}@postgres:5432/${LAKEFS_DB}?sslmode=disable<br>      LAKEFS_AUTH_ENCRYPT_SECRET_KEY: ${LAKEFS_AUTH_ENCRYPT_SECRET_KEY}<br>      LAKEFS_BLOCKSTORE_TYPE: s3<br>      LAKEFS_BLOCKSTORE_S3_ENDPOINT: http://minio:9000<br>      LAKEFS_BLOCKSTORE_S3_FORCE_PATH_STYLE: &quot;true&quot;<br>      LAKEFS_BLOCKSTORE_S3_CREDENTIALS_ACCESS_KEY_ID: ${MINIO_ROOT_USER}<br>      LAKEFS_BLOCKSTORE_S3_CREDENTIALS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD}<br>      LAKEFS_BLOCKSTORE_S3_REGION: us-east-1<br>    ports:<br>      - &quot;8000:8000&quot;<br>    restart: on-failure<br>    healthcheck:<br>      # lakeFS exposes a simple health endpoint on /health in most versions<br>      test: [&quot;CMD-SHELL&quot;, &quot;wget -qO- http://localhost:8000/health &gt;/dev/null 2&gt;&amp;1 || exit 1&quot;]<br>      interval: 5s<br>      timeout: 3s<br>      retries: 60<br>      start_period: 10s<br><br>volumes:<br>  pgdata:<br>  miniodata:<br><br>networks:<br>  signalforge:<br>    name: hybrid-signalforge<br>EOF</pre><h4>2. docker-compose.airflow.yml (orchestration layer)</h4><p>Airflow runs inside a custom image (built earlier), so its runtime already contains our dependencies and providers. This file:</p><ul><li>Initializes Airflow’s metadata schema and creates an admin user (one-time init service).</li><li>Starts the Airflow API/webserver, scheduler, and DAG processor as separate services.</li><li>Mounts dags/ and src/ into the containers so DAG code and shared project code are available.</li><li>Sets conservative local-dev limits (parallelism, max active tasks) to protect Postgres.</li><li>Passes internal service URLs and credentials (MinIO, lakeFS, MLflow, Pushgateway) using environment variables.</li></ul><pre>cat &gt; docker-compose.airflow.yml &lt;&lt; &#39;EOF&#39;<br>services:<br>  airflow-init:<br>    build:<br>      context: .<br>      dockerfile: docker/airflow/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>    env_file:<br>      - .env<br>    environment:<br>      AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>      AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${AIRFLOW_DB_USER}:${AIRFLOW_DB_PASS}@postgres:5432/${AIRFLOW_DB}<br>      AIRFLOW__CORE__LOAD_EXAMPLES: &quot;false&quot;<br>      AIRFLOW__CORE__AUTH_MANAGER: &quot;airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager&quot;<br>      AIRFLOW__CORE__PARALLELISM: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_TASKS_PER_DAG: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG: &quot;1&quot;<br>      AIRFLOW__SCHEDULER__PARSING_PROCESSES: &quot;1&quot;<br><br>      AIRFLOW__API__BASE_URL: http://localhost:8080<br>      AIRFLOW__WEBSERVER__BASE_URL: &quot;http://localhost:8080&quot;<br>      AIRFLOW__API__SECRET_KEY: ${AIRFLOW_API_SECRET_KEY:-signalforge-api-secret}<br>      AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_WEBSERVER_SECRET_KEY:-signalforge-webserver-secret}<br>      AIRFLOW__API_AUTH__JWT_SECRET: ${AIRFLOW_API_AUTH_JWT_SECRET:-signalforge-api-jwt-secret}<br><br>      AIRFLOW__LOGGING__BASE_LOG_FOLDER: /opt/airflow/logs<br>      AIRFLOW__LOGGING__REMOTE_LOGGING: &quot;false&quot;<br><br>      AIRFLOW_WWW_USER_USERNAME: ${AIRFLOW_WWW_USER_USERNAME}<br>      AIRFLOW_WWW_USER_PASSWORD: ${AIRFLOW_WWW_USER_PASSWORD}<br><br>      PYTHONPATH: /opt/airflow/src<br>    volumes:<br>      - ./airflow/dags:/opt/airflow/dags<br>      - ./src:/opt/airflow/src<br>      - airflow_logs:/opt/airflow/logs<br>    command: bash -lc &quot;airflow db migrate &amp;&amp; airflow users create --username \&quot;${AIRFLOW_WWW_USER_USERNAME}\&quot; --password \&quot;${AIRFLOW_WWW_USER_PASSWORD}\&quot; --firstname Admin --lastname User --role Admin --email admin@example.com || true&quot;<br>    restart: &quot;no&quot;<br><br>  airflow-webserver:<br>    build:<br>      context: .<br>      dockerfile: docker/airflow/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      airflow-init:<br>        condition: service_completed_successfully<br>    env_file:<br>      - .env<br>    environment:<br>      AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>      AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${AIRFLOW_DB_USER}:${AIRFLOW_DB_PASS}@postgres:5432/${AIRFLOW_DB}<br>      AIRFLOW__CORE__LOAD_EXAMPLES: &quot;false&quot;<br>      AIRFLOW__CORE__AUTH_MANAGER: &quot;airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager&quot;<br>      AIRFLOW__CORE__PARALLELISM: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_TASKS_PER_DAG: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG: &quot;1&quot;<br>      AIRFLOW__SCHEDULER__PARSING_PROCESSES: &quot;1&quot;<br><br>      AIRFLOW__API__BASE_URL: http://localhost:8080<br>      AIRFLOW__WEBSERVER__BASE_URL: &quot;http://localhost:8080&quot;<br>      AIRFLOW__API__SECRET_KEY: ${AIRFLOW_API_SECRET_KEY:-signalforge-api-secret}<br>      AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_WEBSERVER_SECRET_KEY:-signalforge-webserver-secret}<br>      AIRFLOW__API_AUTH__JWT_SECRET: ${AIRFLOW_API_AUTH_JWT_SECRET:-signalforge-api-jwt-secret}<br><br>      AIRFLOW__LOGGING__BASE_LOG_FOLDER: /opt/airflow/logs<br>      AIRFLOW__LOGGING__REMOTE_LOGGING: &quot;false&quot;<br><br>      PYTHONPATH: /opt/airflow/src<br>      DOCKER_HOST: unix:///var/run/docker.sock<br><br>      AWS_ACCESS_KEY_ID: ${MINIO_ROOT_USER}<br>      AWS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD}<br>      AWS_DEFAULT_REGION: us-east-1<br>      MLFLOW_S3_ENDPOINT_URL: http://minio:9000<br><br>      LAKEFS_ENDPOINT_INTERNAL: ${LAKEFS_ENDPOINT_INTERNAL}<br>      LAKEFS_REPO: ${LAKEFS_REPO}<br>      LAKEFS_STORAGE_NAMESPACE: ${LAKEFS_STORAGE_NAMESPACE:-s3://lakefs/${LAKEFS_REPO}}<br>      LAKEFS_BOOTSTRAP_USERNAME: ${LAKEFS_BOOTSTRAP_USERNAME}<br>      LAKEFS_BOOTSTRAP_ACCESS_KEY_ID: ${LAKEFS_BOOTSTRAP_ACCESS_KEY_ID}<br>      LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY: ${LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY}<br><br>      MINIO_ENDPOINT_INTERNAL: http://minio:9000<br>      MINIO_ROOT_USER: ${MINIO_ROOT_USER}<br>      MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}<br><br>      SIGNALFORGE_N_SAMPLES: ${SIGNALFORGE_N_SAMPLES}<br>      SIGNALFORGE_WINDOW: ${SIGNALFORGE_WINDOW}<br>      SIGNALFORGE_DRIFT_THRESHOLD: ${SIGNALFORGE_DRIFT_THRESHOLD}<br>      MLFLOW_TRACKING_URI: ${MLFLOW_TRACKING_URI}<br>      PUSHGATEWAY_URL: http://pushgateway:9091<br>    ports:<br>      - &quot;8080:8080&quot;<br>    volumes:<br>      - ./airflow/dags:/opt/airflow/dags<br>      - ./src:/opt/airflow/src<br>      - ./spark_jobs:/opt/spark_jobs<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - airflow_logs:/opt/airflow/logs<br>    command: bash -lc &quot;airflow api-server&quot;<br>    healthcheck:<br>      # Airflow 3 API server returns 200 on root<br>      test: [&quot;CMD-SHELL&quot;, &quot;wget -qO- http://localhost:8080/ &gt;/dev/null 2&gt;&amp;1 || exit 1&quot;]<br>      interval: 5s<br>      timeout: 3s<br>      retries: 60<br>      start_period: 20s<br><br>  airflow-scheduler:<br>    build:<br>      context: .<br>      dockerfile: docker/airflow/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      airflow-webserver:<br>        condition: service_healthy<br>      spark-master:<br>        condition: service_started<br>      spark-worker:<br>        condition: service_started<br>    env_file:<br>      - .env<br>    environment:<br>      AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>      AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${AIRFLOW_DB_USER}:${AIRFLOW_DB_PASS}@postgres:5432/${AIRFLOW_DB}<br>      AIRFLOW__CORE__LOAD_EXAMPLES: &quot;false&quot;<br>      AIRFLOW__CORE__AUTH_MANAGER: &quot;airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager&quot;<br>      AIRFLOW__CORE__PARALLELISM: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_TASKS_PER_DAG: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG: &quot;1&quot;<br>      AIRFLOW__SCHEDULER__PARSING_PROCESSES: &quot;1&quot;<br><br>      AIRFLOW__API__BASE_URL: http://airflow-webserver:8080<br>      AIRFLOW__WEBSERVER__BASE_URL: &quot;http://localhost:8080&quot;<br>      AIRFLOW__API__SECRET_KEY: ${AIRFLOW_API_SECRET_KEY:-signalforge-api-secret}<br>      AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_WEBSERVER_SECRET_KEY:-signalforge-webserver-secret}<br>      AIRFLOW__API_AUTH__JWT_SECRET: ${AIRFLOW_API_AUTH_JWT_SECRET:-signalforge-api-jwt-secret}<br><br>      AIRFLOW__LOGGING__BASE_LOG_FOLDER: /opt/airflow/logs<br>      AIRFLOW__LOGGING__REMOTE_LOGGING: &quot;false&quot;<br><br>      PYTHONPATH: /opt/airflow/src<br>      DOCKER_HOST: unix:///var/run/docker.sock<br><br>      AWS_ACCESS_KEY_ID: ${MINIO_ROOT_USER}<br>      AWS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD}<br>      AWS_DEFAULT_REGION: us-east-1<br>      MLFLOW_S3_ENDPOINT_URL: http://minio:9000<br><br>      LAKEFS_ENDPOINT_INTERNAL: ${LAKEFS_ENDPOINT_INTERNAL}<br>      LAKEFS_REPO: ${LAKEFS_REPO}<br>      LAKEFS_STORAGE_NAMESPACE: ${LAKEFS_STORAGE_NAMESPACE:-s3://lakefs/${LAKEFS_REPO}}<br>      LAKEFS_BOOTSTRAP_USERNAME: ${LAKEFS_BOOTSTRAP_USERNAME}<br>      LAKEFS_BOOTSTRAP_ACCESS_KEY_ID: ${LAKEFS_BOOTSTRAP_ACCESS_KEY_ID}<br>      LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY: ${LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY}<br><br>      MINIO_ENDPOINT_INTERNAL: http://minio:9000<br>      MINIO_ROOT_USER: ${MINIO_ROOT_USER}<br>      MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}<br><br>      SIGNALFORGE_N_SAMPLES: ${SIGNALFORGE_N_SAMPLES}<br>      SIGNALFORGE_WINDOW: ${SIGNALFORGE_WINDOW}<br>      SIGNALFORGE_DRIFT_THRESHOLD: ${SIGNALFORGE_DRIFT_THRESHOLD}<br>      MLFLOW_TRACKING_URI: ${MLFLOW_TRACKING_URI}<br>      PUSHGATEWAY_URL: http://pushgateway:9091<br>    volumes:<br>      - ./airflow/dags:/opt/airflow/dags<br>      - ./src:/opt/airflow/src<br>      - ./spark_jobs:/opt/spark_jobs<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - airflow_logs:/opt/airflow/logs<br>    command: bash -lc &quot;airflow scheduler&quot;<br><br>  airflow-dag-processor:<br>    build:<br>      context: .<br>      dockerfile: docker/airflow/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      airflow-webserver:<br>        condition: service_healthy<br>    env_file:<br>      - .env<br>    environment:<br>      AIRFLOW__CORE__EXECUTOR: LocalExecutor<br>      AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://${AIRFLOW_DB_USER}:${AIRFLOW_DB_PASS}@postgres:5432/${AIRFLOW_DB}<br>      AIRFLOW__CORE__LOAD_EXAMPLES: &quot;false&quot;<br>      AIRFLOW__CORE__AUTH_MANAGER: &quot;airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager&quot;<br>      AIRFLOW__CORE__PARALLELISM: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_TASKS_PER_DAG: &quot;2&quot;<br>      AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG: &quot;1&quot;<br>      AIRFLOW__SCHEDULER__PARSING_PROCESSES: &quot;1&quot;<br><br>      AIRFLOW__API__BASE_URL: http://airflow-webserver:8080<br>      AIRFLOW__WEBSERVER__BASE_URL: &quot;http://localhost:8080&quot;<br>      AIRFLOW__API__SECRET_KEY: ${AIRFLOW_API_SECRET_KEY:-signalforge-api-secret}<br>      AIRFLOW__WEBSERVER__SECRET_KEY: ${AIRFLOW_WEBSERVER_SECRET_KEY:-signalforge-webserver-secret}<br>      AIRFLOW__API_AUTH__JWT_SECRET: ${AIRFLOW_API_AUTH_JWT_SECRET:-signalforge-api-jwt-secret}<br><br>      AIRFLOW__LOGGING__BASE_LOG_FOLDER: /opt/airflow/logs<br>      AIRFLOW__LOGGING__REMOTE_LOGGING: &quot;false&quot;<br><br>      PYTHONPATH: /opt/airflow/src<br>    volumes:<br>      - ./airflow/dags:/opt/airflow/dags<br>      - ./src:/opt/airflow/src<br>      - airflow_logs:/opt/airflow/logs<br>    command: bash -lc &quot;airflow dag-processor&quot;<br><br>volumes:<br>  airflow_logs:<br><br>networks:<br>  signalforge:<br>    name: hybrid-signalforge<br>EOF </pre><h4>3. docker-compose.spark.yml (compute layer)</h4><p>Spark is only needed when we reach feature engineering, later section. This file starts:</p><ul><li>A Spark master.</li><li>A Spark worker with capped cores and memory to keep local machines stable.</li></ul><p>We mount spark_jobs/ and src/ read-only into Spark so it can execute our job code without rebuilding.</p><pre>cat &gt; docker-compose.spark.yml &lt;&lt; &#39;EOF&#39;<br>services:<br>  spark-master:<br>    build:<br>      context: .<br>      dockerfile: docker/spark/Dockerfile<br>    image: signalforge-spark:3.5.1<br>    networks:<br>      - signalforge<br>    command: [&quot;/opt/spark/bin/spark-class&quot;, &quot;org.apache.spark.deploy.master.Master&quot;]<br>    environment:<br>      SPARK_MASTER_WEBUI_PORT: 8080<br>      PYTHONPATH: /opt/signalforge/src<br>    ports:<br>      - &quot;7077:7077&quot;<br>      - &quot;8081:8080&quot;<br>    volumes:<br>      - ./spark_jobs:/opt/spark_jobs:ro<br>      - ./src:/opt/signalforge/src:ro<br><br>  spark-worker:<br>    build:<br>      context: .<br>      dockerfile: docker/spark/Dockerfile<br>    image: signalforge-spark:3.5.1<br>    networks:<br>      - signalforge<br>    depends_on:<br>      - spark-master<br>    command: [&quot;/opt/spark/bin/spark-class&quot;, &quot;org.apache.spark.deploy.worker.Worker&quot;, &quot;spark://spark-master:7077&quot;]<br>    environment:<br>      SPARK_WORKER_WEBUI_PORT: 8081<br>      SPARK_WORKER_CORES: 1<br>      SPARK_WORKER_MEMORY: 2g<br>      PYTHONPATH: /opt/signalforge/src<br>    volumes:<br>      - ./spark_jobs:/opt/spark_jobs:ro<br>      - ./src:/opt/signalforge/src:ro<br><br>networks:<br>  signalforge:<br>    name: hybrid-signalforge<br>EOF</pre><h4>4. docker-compose.obs.yml (MLflow + API + monitoring)</h4><p>This file contains the components that rely on “application code being present” (Step 15):</p><p>MLflow server, running in its own lightweight image to speed startup and keep dependencies clean.</p><ul><li>It uses Postgres as the backend store.</li><li>It uses MinIO (S3-compatible) for artifact storage.</li><li>It performs schema initialization or upgrade automatically before starting the server, which avoids common “schema mismatch” failures.</li></ul><p>FastAPI service, built from our API Dockerfile.</p><ul><li>It depends on MLflow being healthy.</li><li>It will later load the “Production” model from the MLflow registry and serve predictions.</li></ul><p>And:</p><ul><li>Pushgateway for batch-pushed drift metrics.</li><li>Prometheus to scrape metrics from FastAPI and Pushgateway.</li><li>Grafana with provisioning for datasource and dashboard paths, plus a persistent volume for state.</li></ul><pre>cat &gt; docker/mlflow/Dockerfile &lt;&lt; &#39;EOF&#39;<br>FROM python:3.11-slim<br><br># Install curl for the healthcheck (slim images often do not include it)<br>RUN apt-get update \<br>  &amp;&amp; apt-get install -y --no-install-recommends curl \<br>  &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>WORKDIR /app<br><br># Copy requirements into the image and install at build time<br>COPY requirements.mlflow.txt /app/requirements.txt<br>RUN pip install --no-cache-dir -r /app/requirements.txt<br><br>EXPOSE 5000<br><br># Run MLflow server (reads env vars injected by compose)<br>CMD [&quot;sh&quot;, &quot;-lc&quot;, &quot;\<br>mlflow server \<br>  --host 0.0.0.0 \<br>  --port 5000 \<br>  --backend-store-uri postgresql+psycopg2://${MLFLOW_DB_USER}:${MLFLOW_DB_PASS}@postgres:5432/${MLFLOW_DB} \<br>  --default-artifact-root s3://${MLFLOW_ARTIFACT_BUCKET}/ \<br>&quot;]<br>EOF</pre><pre>cat &gt; docker-compose.obs.yml &lt; &#39;EOF&#39;<br>services:<br>  mlflow:<br>    build:<br>      context: .<br>      dockerfile: docker/mlflow/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      postgres:<br>        condition: service_healthy<br>      minio:<br>        condition: service_started<br>    env_file:<br>      - .env<br>    environment:<br>      MLFLOW_TRACKING_URI: http://mlflow:5000<br>      AWS_ACCESS_KEY_ID: ${MINIO_ROOT_USER}<br>      AWS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD}<br>      MLFLOW_S3_ENDPOINT_URL: http://minio:9000<br>    ports:<br>      - &quot;5000:5000&quot;<br>    command: &gt;<br>      sh -lc &quot;python -c \&quot;from mlflow.store.db import utils; uri=&#39;postgresql+psycopg2://${MLFLOW_DB_USER}:${MLFLOW_DB_PASS}@postgres:5432/${MLFLOW_DB}&#39;; engine=utils.create_sqlalchemy_engine_with_retry(uri); rev=utils._get_schema_version(engine); utils._initialize_tables(engine) if rev is None else utils._upgrade_db(engine)\&quot; &amp;&amp;<br>      mlflow server --host 0.0.0.0 --port 5000 --backend-store-uri postgresql+psycopg2://${MLFLOW_DB_USER}:${MLFLOW_DB_PASS}@postgres:5432/${MLFLOW_DB} --default-artifact-root s3://${MLFLOW_ARTIFACT_BUCKET}/&quot;<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;curl -fsS http://localhost:5000/ &gt;/dev/null 2&gt;&amp;1 || exit 1&quot;]<br>      interval: 5s<br>      timeout: 3s<br>      retries: 30<br>      start_period: 20s<br><br>  api:<br>    build:<br>      context: .<br>      dockerfile: api/Dockerfile<br>    networks:<br>      - signalforge<br>    depends_on:<br>      mlflow:<br>        condition: service_healthy<br>    env_file:<br>      - .env<br>    environment:<br>      MLFLOW_TRACKING_URI: http://mlflow:5000<br>      MODEL_NAME: rf_modulation_classifier<br>      MODEL_STAGE: Production<br>      AWS_ACCESS_KEY_ID: ${MINIO_ROOT_USER}<br>      AWS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD}<br>      MLFLOW_S3_ENDPOINT_URL: http://minio:9000<br>    ports:<br>      - &quot;${API_PORT:-9000}:9000&quot;<br><br>  pushgateway:<br>    image: prom/pushgateway:v1.8.0<br>    networks:<br>      - signalforge<br>    ports:<br>      - &quot;9091:9091&quot;<br><br>  prometheus:<br>    image: prom/prometheus:v2.54.1<br>    networks:<br>      - signalforge<br>    depends_on:<br>      - pushgateway<br>      - api<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro<br><br>  grafana:<br>    image: grafana/grafana:11.1.4<br>    networks:<br>      - signalforge<br>    depends_on:<br>      - prometheus<br>    ports:<br>      - &quot;3000:3000&quot;<br>    env_file:<br>      - .env<br>    environment:<br>      GF_SECURITY_ADMIN_USER: admin<br>      GF_SECURITY_ADMIN_PASSWORD: admin<br>    volumes:<br>      - grafanadata:/var/lib/grafana<br>      - ./docker/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro<br>      - ./docker/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro<br>      - ./docker/grafana/dashboards:/var/lib/grafana/dashboards<br><br>volumes:<br>  grafanadata:<br><br>networks:<br>  signalforge:<br>    name: hybrid-signalforge<br>EOF</pre><blockquote>Networking Note: Service-name DNS like <a href="http://mlflow:5000/">http://mlflow:5000</a> works only inside the Compose network. It will not resolve from your host machine. That is why we publish host ports for UIs (localhost:5000, localhost:8080, etc.), but containers talk to each other using service names.</blockquote><h4>5. docker-compose.yml (the “include” wrapper)</h4><p>To make the platform easy to run, we create a top-level compose file that includes the other compose files. This lets us bring everything up together later, while still keeping the ability to start only the parts we need during development.</p><pre>cat &gt; docker-compose.yml &lt;&lt; &#39;EOF&#39;<br>include:<br>  - docker-compose.base.yml<br>  - docker-compose.airflow.yml<br>  - docker-compose.spark.yml<br>  - docker-compose.obs.yml<br>EOF</pre><h4>Next: commands to run (incremental bring-up)</h4><p>We start with the base layer first to confirm Postgres, MinIO, and lakeFS are healthy:</p><ul><li>Bring up the base stack.</li><li>Check container status (docker compose ps) and confirm the UIs respond.</li></ul><pre># You may need to build the image if this is your first time: <br># docker compose -f docker-compose.base.yml up -d --build<br><br>docker compose -f docker-compose.base.yml up -d<br>docker compose ps</pre><p>You should see containers running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAXepVG_29Kua5Gu1MY6Qg.png" /><figcaption>Fig: Base containers running</figcaption></figure><p>This incremental approach keeps debugging manageable and prevents “everything fails at once” scenarios.</p><h3>Step 7: Create a reusable project package (src/signalforge/…)</h3><p>Now we start building src/signalforge as a proper Python package so both Airflow tasks and the FastAPI service can import shared logic cleanly. This is an important platform habit: instead of writing one-off scripts per step, we build reusable internal libraries that multiple services can depend on.</p><p>What we are doing in this step (high level):</p><ul><li>We create a src/ layout package (src/signalforge), so our codebase behaves like a real Python module, not a folder of loose scripts.</li><li>We add an __init__.py so Python treats the directory as an importable package.</li><li>We introduce a config module that becomes the single source of truth for runtime settings across the platform.</li></ul><h4>Why the config module matters</h4><p>In a multi-service system, the biggest source of bugs is inconsistent configuration. Airflow runs inside one container, the API runs in another, Spark runs elsewhere, and each service has its own environment. By reading configuration from environment variables in one place, we ensure:</p><ul><li>Airflow tasks and the API resolve the same service endpoints (lakeFS, MLflow, Pushgateway) using Docker network DNS names.</li><li>Defaults exist for local development, but missing critical variables still fail fast with a clear error.</li><li>Types are enforced for numeric settings (sample counts, window sizes, drift thresholds) so we do not accidentally treat numbers as strings.</li></ul><h4>What the initial configuration covers</h4><ul><li>lakeFS connectivity and repo settings (internal endpoint and repo name).</li><li>lakeFS bootstrap credentials for initial setup automation.</li><li>dataset generation controls (number of samples, signal window size).</li><li>drift configuration (thresholds used later by monitoring logic).</li><li>MLflow tracking URI and Pushgateway URL so training, serving, and drift reporting can share the same wiring.</li></ul><pre>mkdir -p src/signalforge</pre><pre>cat &gt; src/signalforge/__init__.py &lt;&lt; &#39;EOF&#39;<br>__all__ = []<br>EOF</pre><pre>cat &gt; src/signalforge/config.py &lt;&lt; &#39;EOF&#39;<br>import os<br>from typing import Optional<br><br>def env(name: str, default: Optional[str] = None, *, allow_empty: bool = False) -&gt; str:<br>    &quot;&quot;&quot;<br>    Reads an env var.<br>    - If var is missing OR empty (unless allow_empty=True), fall back to default.<br>    - If still missing, raise.<br>    &quot;&quot;&quot;<br>    v = os.environ.get(name)<br><br>    if v is None or (not allow_empty and v.strip() == &quot;&quot;):<br>        if default is not None:<br>            return default<br>        raise RuntimeError(f&quot;Missing env var: {name}&quot;)<br><br>    return v<br><br>LAKEFS_ENDPOINT_INTERNAL = env(&quot;LAKEFS_ENDPOINT_INTERNAL&quot;, &quot;http://lakefs:8000&quot;)<br>LAKEFS_REPO = env(&quot;LAKEFS_REPO&quot;, &quot;signalforge&quot;)<br><br>LAKEFS_BOOTSTRAP_USERNAME = env(&quot;LAKEFS_BOOTSTRAP_USERNAME&quot;, &quot;admin&quot;)<br>LAKEFS_BOOTSTRAP_ACCESS_KEY_ID = env(&quot;LAKEFS_BOOTSTRAP_ACCESS_KEY_ID&quot;, &quot;AKIASIGNALFORGE00001&quot;)<br>LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY = env(&quot;LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY&quot;, &quot;signalforgeSecretKeyLocalMinio0000000000&quot;)<br><br>SIGNALFORGE_N_SAMPLES = int(env(&quot;SIGNALFORGE_N_SAMPLES&quot;, &quot;3000&quot;))<br>SIGNALFORGE_WINDOW = int(env(&quot;SIGNALFORGE_WINDOW&quot;, &quot;1024&quot;))<br>SIGNALFORGE_DRIFT_THRESHOLD = float(env(&quot;SIGNALFORGE_DRIFT_THRESHOLD&quot;, &quot;0.6&quot;))<br><br>MLFLOW_TRACKING_URI = env(&quot;MLFLOW_TRACKING_URI&quot;, &quot;http://mlflow:5000&quot;)<br>PUSHGATEWAY_URL = env(&quot;PUSHGATEWAY_URL&quot;, &quot;http://pushgateway:9091&quot;)<br>EOF</pre><p>As we move forward, we will keep adding modules under src/signalforge for the rest of the platform logic (data generation, lakeFS operations, quality gates, training, drift checks, and feature extraction), and both Airflow and the API will consume those modules instead of duplicating code.</p><h3>Step 8: lakeFS bootstrap and operations</h3><p>In this step, we add two small but important building blocks around lakeFS:</p><p>1) A bootstrap routine that:</p><ul><li>waits for lakeFS to be reachable,</li><li>performs first-time admin setup (only if it has not been done yet),</li><li>creates the lakeFS repository programmatically (only if it does not exist yet),</li><li>and (best effort) ensures the underlying object-storage bucket exists.</li></ul><p>2) A reusable “operations” layer that:</p><ul><li>provides consistent clients for both the lakeFS HTTP API and the lakeFS S3 gateway,</li><li>and exposes safe, idempotent helper functions (create branch, commit, merge, and simple existence checks).</li></ul><h4>Why this matters</h4><p>Doing bootstrap in code removes manual clicks in the UI and makes the platform reproducible. This is a core platform engineering skill: automate the “first 10 minutes,” so any developer can bring up the stack, run one command, and get a ready-to-use versioned data lake.</p><h4>What is happening in the bootstrap module (high-level)</h4><p>The bootstrap logic is designed to be idempotent, meaning it is safe to run multiple times. It follows a clear sequence:</p><ul><li>Ensure the storage bucket exists: lakeFS repositories map to a storage namespace (S3-style path). Before creating or using a repo, we make sure the target bucket is present in MinIO (or we rely on the Compose MinIO bootstrap container if credentials are not available in this runtime).</li><li>Wait for lakeFS: services start at different speeds, so we poll lakeFS endpoints until it responds. This prevents “connection refused” failures in early startup.</li><li>Check setup state: lakeFS has a one-time setup step. If it is not set up yet, we create the initial admin user and access keys.</li><li>Create the repository: using the authenticated lakeFS API, we create the repo if it is missing, and set a default main branch.</li><li>Handle races safely: if another process created the repo or completed setup in parallel, we treat “already exists” as success.</li></ul><h4>What is happening in the operations module (high level)</h4><p>The operations layer standardizes how the rest of the project talks to lakeFS:</p><ul><li>It defines a small context object that captures the repo name, endpoint, and credentials in one place.</li><li>It constructs a lakeFS API client for HTTP calls (repos, branches, commits, merges).</li><li>It constructs an S3 client that targets the lakeFS S3 gateway, so normal S3 operations (upload, download, list) are version-aware through branches and commits.</li></ul><p>It provides guard rails:</p><ul><li>fail fast if the repository does not exist,</li><li>fail fast if the S3 gateway bucket is not accessible,</li><li>and implement idempotent branch creation so reruns do not break pipelines.</li></ul><p>And, it exposes the core version-control primitives we’ll use later: create branch, commit changes, merge branch.</p><pre>cat &gt; src/signalforge/lakefs_bootstrap.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import os<br>import time<br>from urllib.parse import urlparse<br><br>import boto3<br>import requests<br>import lakefs_client<br>from lakefs_client.api import internal_api, repositories_api<br>from lakefs_client.models import Setup, AccessKeyCredentials, RepositoryCreation<br>from lakefs_client import ApiException<br><br><br>LAKEFS_ENDPOINT_INTERNAL = os.getenv(&quot;LAKEFS_ENDPOINT_INTERNAL&quot;, &quot;http://lakefs:8000&quot;).rstrip(&quot;/&quot;)<br>LAKEFS_REPO = os.getenv(&quot;LAKEFS_REPO&quot;, &quot;signalforge&quot;)<br><br>LAKEFS_STORAGE_NAMESPACE = os.getenv(&quot;LAKEFS_STORAGE_NAMESPACE&quot;, f&quot;s3://lakefs/{LAKEFS_REPO}&quot;).rstrip(&quot;/&quot;)<br><br>LAKEFS_BOOTSTRAP_USERNAME = os.getenv(&quot;LAKEFS_BOOTSTRAP_USERNAME&quot;, &quot;admin&quot;)<br>LAKEFS_BOOTSTRAP_ACCESS_KEY_ID = os.getenv(&quot;LAKEFS_BOOTSTRAP_ACCESS_KEY_ID&quot;, &quot;admin&quot;)<br>LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY = os.getenv(&quot;LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY&quot;, &quot;adminadminadmin&quot;)<br><br>MINIO_ENDPOINT_INTERNAL = os.getenv(&quot;MINIO_ENDPOINT_INTERNAL&quot;, &quot;http://minio:9000&quot;).rstrip(&quot;/&quot;)<br>MINIO_ROOT_USER = os.getenv(&quot;MINIO_ROOT_USER&quot;, &quot;&quot;)<br>MINIO_ROOT_PASSWORD = os.getenv(&quot;MINIO_ROOT_PASSWORD&quot;, &quot;&quot;)<br><br><br>def _parse_storage_bucket(storage_namespace: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    storage_namespace looks like: s3://&lt;bucket&gt;/&lt;prefix&gt;<br>    We need the bucket to exist in MinIO.<br>    &quot;&quot;&quot;<br>    if not storage_namespace.startswith(&quot;s3://&quot;):<br>        raise ValueError(f&quot;Unsupported LAKEFS_STORAGE_NAMESPACE: {storage_namespace}&quot;)<br>    parsed = urlparse(storage_namespace)<br>    # urlparse(&quot;s3://lakefs/signalforge&quot;) -&gt; netloc=&quot;lakefs&quot;, path=&quot;/signalforge&quot;<br>    return parsed.netloc<br><br><br>def ensure_minio_bucket(bucket: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Best-effort: create bucket in MinIO if creds are provided.<br>    If creds are missing, we skip (compose minio-mc can still handle it).<br>    &quot;&quot;&quot;<br>    if not MINIO_ROOT_USER or not MINIO_ROOT_PASSWORD:<br>        return<br><br>    s3 = boto3.client(<br>        &quot;s3&quot;,<br>        endpoint_url=MINIO_ENDPOINT_INTERNAL,<br>        aws_access_key_id=MINIO_ROOT_USER,<br>        aws_secret_access_key=MINIO_ROOT_PASSWORD,<br>        region_name=&quot;us-east-1&quot;,<br>    )<br><br>    # Head bucket first<br>    try:<br>        s3.head_bucket(Bucket=bucket)<br>        return<br>    except Exception:<br>        pass<br><br>    # Create<br>    try:<br>        s3.create_bucket(Bucket=bucket)<br>    except Exception:<br>        # Race / already exists, ignore.<br>        return<br><br><br>def wait_for_lakefs(endpoint: str, timeout_s: int = 120) -&gt; None:<br>    &quot;&quot;&quot;<br>    Wait for lakeFS HTTP to respond.<br>    &quot;&quot;&quot;<br>    deadline = time.time() + timeout_s<br>    url_candidates = [<br>        f&quot;{endpoint}/health&quot;,<br>        f&quot;{endpoint}/&quot;,<br>        f&quot;{endpoint}/api/v1/setup&quot;,<br>    ]<br><br>    last_err = None<br>    while time.time() &lt; deadline:<br>        for url in url_candidates:<br>            try:<br>                r = requests.get(url, timeout=3)<br>                if r.status_code in (200, 401, 404):<br>                    return<br>            except Exception as e:<br>                last_err = e<br>        time.sleep(2)<br><br>    raise RuntimeError(f&quot;lakeFS not reachable in time. last_err={last_err!r}&quot;)<br><br><br>def ensure_setup_and_repo() -&gt; bool:<br>    &quot;&quot;&quot;<br>    Ensure:<br>      1) lakeFS is bootstrapped (setup completed) with an admin user + access keys<br>      2) the target repository exists (create it if missing)<br>      3) the underlying MinIO bucket for storage_namespace exists (best-effort)<br><br>    Idempotent: safe to run multiple times.<br>    &quot;&quot;&quot;<br>    # 0) Ensure underlying bucket exists<br>    bucket = _parse_storage_bucket(LAKEFS_STORAGE_NAMESPACE)<br>    ensure_minio_bucket(bucket)<br><br>    # 1) Wait for lakeFS<br>    wait_for_lakefs(LAKEFS_ENDPOINT_INTERNAL)<br><br>    # 2) Internal setup check (unauthenticated)<br>    host = f&quot;{LAKEFS_ENDPOINT_INTERNAL}/api/v1&quot;<br>    cfg = lakefs_client.Configuration(host=host)<br><br>    did_setup = False<br>    created_repo = False<br><br>    with lakefs_client.ApiClient(cfg) as api_client:<br>        internal = internal_api.InternalApi(api_client)<br>        state = internal.get_setup_state()<br><br>        if not getattr(state, &quot;is_setup&quot;, False):<br>            setup = Setup(<br>                username=LAKEFS_BOOTSTRAP_USERNAME,<br>                key=AccessKeyCredentials(<br>                    access_key_id=LAKEFS_BOOTSTRAP_ACCESS_KEY_ID,<br>                    secret_access_key=LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY,<br>                ),<br>            )<br>            try:<br>                internal.setup(setup)<br>                did_setup = True<br>            except ApiException as e:<br>                if e.status != 409:<br>                    raise<br><br>    # 3) Authenticated repository operations<br>    auth_cfg = lakefs_client.Configuration(<br>        host=host,<br>        username=LAKEFS_BOOTSTRAP_ACCESS_KEY_ID,<br>        password=LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY,<br>    )<br><br>    with lakefs_client.ApiClient(auth_cfg) as auth_client:<br>        repos = repositories_api.RepositoriesApi(auth_client)<br><br>        try:<br>            repos.get_repository(LAKEFS_REPO)<br>            return did_setup or created_repo<br>        except ApiException as e:<br>            if e.status != 404:<br>                raise<br><br>        repo_creation = RepositoryCreation(<br>            name=LAKEFS_REPO,<br>            storage_namespace=LAKEFS_STORAGE_NAMESPACE,<br>            default_branch=&quot;main&quot;,<br>        )<br><br>        try:<br>            repos.create_repository(repo_creation)<br>            created_repo = True<br>        except ApiException as e:<br>            # Handle race if another worker created it.<br>            if e.status in (409, 422):<br>                return did_setup or created_repo<br>            raise<br>    return did_setup or created_repo<br><br><br>def main() -&gt; None:<br>    created = ensure_setup_and_repo()<br>    if created:<br>        print(&quot;lakeFS setup complete, repo ready&quot;)<br>    else:<br>        print(&quot;lakeFS already set up, repo ready&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br>EOF</pre><pre>cat &gt; src/signalforge/lakefs_ops.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>from dataclasses import dataclass<br>from typing import Optional<br><br>import boto3<br>from botocore.config import Config<br><br>import lakefs_client<br>from lakefs_client import Configuration<br>from lakefs_client.api import branches_api, commits_api, refs_api, repositories_api<br>from lakefs_client import ApiException<br><br><br>@dataclass(frozen=True)<br>class LakeFSContext:<br>    repo: str<br>    endpoint: str  # e.g. http://lakefs:8000 (NOT /api/v1)<br>    access_key_id: str<br>    secret_access_key: str<br><br><br>def lakefs_api_config(ctx: LakeFSContext) -&gt; Configuration:<br>    return lakefs_client.Configuration(<br>        host=f&quot;{ctx.endpoint.rstrip(&#39;/&#39;)}/api/v1&quot;,<br>        username=ctx.access_key_id,<br>        password=ctx.secret_access_key,<br>    )<br><br><br>def lakefs_s3_client(ctx: LakeFSContext):<br>    &quot;&quot;&quot;<br>    S3 client targeting lakeFS S3 gateway (same host:8000).<br>    IMPORTANT: bucket name is the lakeFS repo name.<br>    &quot;&quot;&quot;<br>    return boto3.client(<br>        &quot;s3&quot;,<br>        endpoint_url=ctx.endpoint.rstrip(&quot;/&quot;),<br>        aws_access_key_id=ctx.access_key_id,<br>        aws_secret_access_key=ctx.secret_access_key,<br>        region_name=&quot;us-east-1&quot;,<br>        config=Config(s3={&quot;addressing_style&quot;: &quot;path&quot;}),<br>    )<br><br><br>def ensure_repo_exists(ctx: LakeFSContext) -&gt; None:<br>    &quot;&quot;&quot;<br>    Ensures the repository exists (or raises clearly).<br>    Repo creation is handled in lakefs_bootstrap.py; this is a guard.<br>    &quot;&quot;&quot;<br>    cfg = lakefs_api_config(ctx)<br>    with lakefs_client.ApiClient(cfg) as api_client:<br>        repos = repositories_api.RepositoriesApi(api_client)<br>        try:<br>            repos.get_repository(ctx.repo)<br>        except ApiException as e:<br>            if e.status == 404:<br>                raise RuntimeError(<br>                    f&quot;lakeFS repository &#39;{ctx.repo}&#39; not found. &quot;<br>                    &quot;Run bootstrap_lakefs first (or fix LAKEFS_REPO / credentials).&quot;<br>                ) from e<br>            raise<br><br><br>def ensure_repo_visible_via_s3(ctx: LakeFSContext) -&gt; None:<br>    &quot;&quot;&quot;<br>    Fail-fast check for the lakeFS S3 gateway bucket.<br>    This avoids confusing NoSuchBucket later during upload/download.<br>    &quot;&quot;&quot;<br>    s3 = lakefs_s3_client(ctx)<br>    try:<br>        s3.head_bucket(Bucket=ctx.repo)<br>    except Exception as e:<br>        raise RuntimeError(<br>            f&quot;lakeFS S3 gateway bucket &#39;{ctx.repo}&#39; is not accessible. &quot;<br>            &quot;This usually means the repo does not exist OR credentials are wrong.&quot;<br>        ) from e<br><br><br>def create_branch(ctx: LakeFSContext, source_ref: str, new_branch: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Idempotent branch creation:<br>    - If exists, do nothing.<br>    - Else create from source_ref.<br>    &quot;&quot;&quot;<br>    ensure_repo_exists(ctx)<br><br>    cfg = lakefs_api_config(ctx)<br>    with lakefs_client.ApiClient(cfg) as api_client:<br>        branches = branches_api.BranchesApi(api_client)<br><br>        # Exists?<br>        try:<br>            branches.get_branch(repository=ctx.repo, branch=new_branch)<br>            return<br>        except ApiException as e:<br>            if e.status != 404:<br>                raise<br><br>        # Create<br>        try:<br>            branches.create_branch(<br>                repository=ctx.repo,<br>                branch_creation={<br>                    &quot;name&quot;: new_branch,<br>                    &quot;source&quot;: source_ref,<br>                },<br>            )<br>        except ApiException as e:<br>            # Handle race: created by another worker<br>            if e.status in (409, 422):<br>                return<br>            raise<br><br><br>def commit_changes(ctx: LakeFSContext, branch: str, message: str) -&gt; str:<br>    ensure_repo_exists(ctx)<br><br>    cfg = lakefs_api_config(ctx)<br>    with lakefs_client.ApiClient(cfg) as api_client:<br>        commits = commits_api.CommitsApi(api_client)<br>        resp = commits.commit(<br>            repository=ctx.repo,<br>            branch=branch,<br>            commit_creation={&quot;message&quot;: message},<br>        )<br>        return resp.id<br><br><br>def merge_branch(ctx: LakeFSContext, source_branch: str, destination_branch: str) -&gt; None:<br>    ensure_repo_exists(ctx)<br><br>    cfg = lakefs_api_config(ctx)<br>    with lakefs_client.ApiClient(cfg) as api_client:<br>        refs = refs_api.RefsApi(api_client)<br>        refs.merge_into_branch(<br>            repository=ctx.repo,<br>            source_ref=source_branch,<br>            destination_branch=destination_branch,<br>        )<br>EOF</pre><h4>How we verify bootstrap works</h4><p>After the base and Airflow services are running, we execute the bootstrap module inside the running Airflow container. This is intentional: Airflow is the orchestration environment, so validating from inside it ensures that service DNS, credentials, and network wiring are correct.</p><pre>docker compose exec airflow-webserver python -m signalforge.lakefs_bootstrap</pre><p>When you run the bootstrap command, it:</p><ul><li>connects to the lakeFS service over the Docker network,</li><li>checks whether lakeFS has already been initialized,</li><li>performs admin setup only if required,</li><li>and ensures the signalforge repository exists with a default main branch.</li></ul><p>If everything is wired correctly, you should see a message indicating lakeFS is already ready or that setup was completed and the repository is ready for use.</p><h3>Step 9: Generate and store realistic signal data</h3><p>Now we generate a realistic synthetic dataset that looks like test-and-measurement RF/sensor data. The goal is to create baseband I/Q windows (complex samples) with controlled, realistic impairments such as noise, carrier frequency offset (CFO), and phase shift. We then store the outputs in two complementary formats:</p><ul><li>A Parquet dataset for structured, scalable processing in Spark and downstream training.</li><li>A JSON manifest for semi-structured metadata that is easy to inspect, version, and audit.</li></ul><p>This “structured + semi-structured” pattern is common in real platforms. The Parquet file is optimized for pipelines and analytics, while the manifest preserves run-level context for reproducibility and debugging.</p><h4>What the generator produces</h4><p>For each example (one row/sample), we generate:</p><ul><li>A modulation label (classification target), sampled from a small set like BPSK, QPSK, 16QAM, and 64QAM.</li><li>A window of complex baseband samples represented as separate I and Q arrays (lists), each of length = window size.</li></ul><p>Per-sample impairment parameters that simulate real-world effects:</p><ul><li>SNR in dB, sampled from a range to produce varying noise conditions.</li><li>CFO as a normalized offset (cycles per sample), applied as a rotating complex phasor over time.</li><li>A constant phase offset (radians), applied as a rotation of the entire constellation.</li></ul><p>And, Traceability fields like a unique sample_id and a run_id, so every row can be tracked back to its generation run.</p><h4>How the signal is synthesized (conceptually)</h4><p>The generation flow mirrors a simplified comms receiver chain:</p><p>1) Choose a modulation scheme and sample ideal constellation symbols.</p><p>2) Apply deterministic channel impairments first:</p><ul><li>CFO (time-varying phase rotation across the window)</li><li>then a constant phase shift (global rotation)</li></ul><p>3) Add complex AWGN to achieve the sampled SNR.</p><p>4) Split the complex signal into I and Q arrays and store them in a row-friendly format.</p><h4>Why we write Parquet</h4><p>Parquet (via Arrow) gives us efficient columnar storage, good compression, and fast reads. It is ideal for Spark feature engineering and model training workflows. Storing I and Q as list columns keeps each example self-contained while still being scalable for batch processing.</p><p>Sample: raw_&lt;run_id&gt;.parquet (one row example)</p><pre>{<br>  &quot;sample_id&quot;: &quot;6d6d8c90-9c3f-4c1c-9c5a-6e7a5f0c2f12&quot;,<br>  &quot;run_id&quot;: &quot;run_20260118T012345Z_ab12cd34&quot;,<br>  &quot;modulation&quot;: &quot;QPSK&quot;,<br>  &quot;snr_db&quot;: 18.42,<br>  &quot;cfo&quot;: -0.0087,<br>  &quot;phi&quot;: 1.24,<br>  &quot;i&quot;: [0.65, -0.72, 0.69, ...],<br>  &quot;q&quot;: [-0.70, 0.68, -0.73, ...]<br>}</pre><p>Sample: Parquet schema (columns)</p><pre>sample_id: string<br>run_id: string<br>modulation: string<br>snr_db: double<br>cfo: double<br>phi: double<br>i: list&lt;float&gt;<br>q: list&lt;float&gt;</pre><h4>Why we also write a JSON manifest</h4><p>The manifest captures batch-level parameters such as:</p><ul><li>run_id</li><li>sample count and window size</li><li>supported modulation set</li><li>SNR range and CFO range</li></ul><p>This makes the dataset reproducible, debuggable, and easy to compare across versions when we later introduce drift or change generation settings.</p><p>Sample: manifest_&lt;run_id&gt;.json</p><pre>{<br>  &quot;run_id&quot;: &quot;run_20260118T012345Z_ab12cd34&quot;,<br>  &quot;n_samples&quot;: 3000,<br>  &quot;window&quot;: 1024,<br>  &quot;mods&quot;: [&quot;BPSK&quot;, &quot;QPSK&quot;, &quot;16QAM&quot;, &quot;64QAM&quot;],<br>  &quot;snr_db_low&quot;: 5.0,<br>  &quot;snr_db_high&quot;: 25.0,<br>  &quot;cfo_abs_max&quot;: 0.02<br>}</pre><h4>Default settings</h4><p>We keep a default “spec” (configuration) that pulls the sample count and window length from our central config, and sets reasonable starting ranges for SNR and CFO. Later, we can intentionally shift these ranges to simulate distribution drift and test the monitoring pipeline.</p><pre>cat &gt; src/signalforge/data_gen.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import json<br>import math<br>import os<br>import uuid<br>from dataclasses import dataclass  # Used to define a small immutable config container (BatchSpec).<br>from typing import Iterable<br><br>import numpy as np  # Main numeric library for vectorized signal generation and random sampling.<br>import pyarrow as pa  # Used to build a columnar table efficiently.<br>import pyarrow.parquet as pq  # Used to write the table into a Parquet file.<br><br>from signalforge.config import SIGNALFORGE_N_SAMPLES, SIGNALFORGE_WINDOW<br># Imports default configuration constants for:<br># - how many samples to generate per batch<br># - how many complex samples are in each example (window length)<br><br># List of modulation formats supported by this generator.<br>MODS = [&quot;BPSK&quot;, &quot;QPSK&quot;, &quot;16QAM&quot;, &quot;64QAM&quot;]<br><br>def _constellation(mod: str) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Return the complex constellation points (I + jQ) for a given modulation scheme.<br><br>    Output:<br>      A 1D numpy array of complex numbers representing ideal symbol locations.<br>      Constellations are normalized so average symbol power is ~1 (helps SNR math).<br>    &quot;&quot;&quot;<br>    if mod == &quot;BPSK&quot;:<br>        # Binary PSK: two symbols on the real axis.<br>        return np.array([-1+0j, 1+0j])<br><br>    if mod == &quot;QPSK&quot;:<br>        # Quadrature PSK: four symbols at the corners of a square.<br>        # Divide by sqrt(2) to normalize average symbol power to 1.<br>        return np.array([1+1j, 1-1j, -1+1j, -1-1j]) / math.sqrt(2)<br><br>    if mod == &quot;16QAM&quot;:<br>        # 16-QAM: 4x4 grid with I and Q values in {-3, -1, 1, 3}.<br>        # Normalize by sqrt(10) so average symbol power is ~1.<br>        pts = []<br>        for i in [-3, -1, 1, 3]:<br>            for q in [-3, -1, 1, 3]:<br>                pts.append(i + 1j*q)<br>        pts = np.array(pts) / math.sqrt((10))<br>        return pts<br><br>    if mod == &quot;64QAM&quot;:<br>        # 64-QAM: 8x8 grid with I and Q values in {-7, -5, -3, -1, 1, 3, 5, 7}.<br>        # Normalize by sqrt(42) so average symbol power is ~1.<br>        vals = [-7, -5, -3, -1, 1, 3, 5, 7]<br>        pts = np.array([i + 1j*q for i in vals for q in vals]) / math.sqrt(42)<br>        return pts<br><br>    # If an unknown modulation is passed, fail early with an explicit error.<br>    raise ValueError(mod)<br><br>def _awgn(x: np.ndarray, snr_db: float) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Add complex Additive White Gaussian Noise (AWGN) to a complex baseband signal.<br><br>    Args:<br>      x: complex numpy array (signal)<br>      snr_db: desired SNR in dB, defined as signal_power / noise_power<br><br>    Steps:<br>      1) Estimate the signal power from the generated signal (mean |x|^2).<br>      2) Convert SNR from dB to linear.<br>      3) Compute noise power needed to achieve that SNR.<br>      4) Generate complex Gaussian noise with that power:<br>         - real and imag parts are independent N(0, sigma^2)<br>         - for complex noise, each component gets half the total noise power.<br>      5) Return x + noise.<br>    &quot;&quot;&quot;<br>    # Average signal power (per sample).<br>    sig_pow = np.mean(np.abs(x)**2)<br><br>    # Convert dB to linear SNR.<br>    snr = 10 ** (snr_db / 10.0)<br><br>    # noise_power = signal_power / SNR<br>    noise_pow = sig_pow / snr<br><br>    # Create complex Gaussian noise:<br>    # Each of I and Q has variance = noise_pow / 2.<br>    noise = (np.random.normal(scale=math.sqrt(noise_pow/2), size=x.shape) +<br>             1j*np.random.normal(scale=math.sqrt(noise_pow/2), size=x.shape))<br><br>    # Noisy received signal.<br>    return x + noise<br><br>def _apply_cfo(x: np.ndarray, cfo: float) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Apply Carrier Frequency Offset (CFO) to a complex baseband signal.<br><br>    Args:<br>      x: complex numpy array, length N<br>      cfo: normalized CFO in cycles/sample (not Hz).<br>           Example: cfo = 0.01 means 0.01 cycles per sample,<br>           which equals a phase increment of 2*pi*0.01 radians per sample.<br><br>    Method:<br>      Multiply the signal by a complex rotating phasor exp(j*2*pi*cfo*n).<br>    &quot;&quot;&quot;<br>    # cfo is normalized cycles/sample<br>    n = np.arange(x.shape[0], dtype=np.float64)   # sample indices 0..N-1<br>    rot = np.exp(1j * 2 * math.pi * cfo * n)      # complex rotation per sample<br>    return x * rot<br><br>def _apply_phase(x: np.ndarray, phi: float) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Apply a constant phase offset to the signal.<br><br>    Args:<br>      x: complex numpy array<br>      phi: phase offset in radians<br><br>    Method:<br>      Multiply by exp(j*phi), which rotates the entire constellation by phi.<br>    &quot;&quot;&quot;<br>    return x * np.exp(1j * phi)<br><br>@dataclass(frozen=True)<br>class BatchSpec:<br>    &quot;&quot;&quot;<br>    Immutable configuration for one synthetic dataset generation run (one batch).<br><br>    Fields:<br>      n_samples: number of examples (rows) to generate<br>      window: number of symbols/samples per example<br>      snr_db_low/high: uniform random SNR range in dB for each example<br>      cfo_abs_max: CFO sampled uniformly from [-cfo_abs_max, +cfo_abs_max]<br>    &quot;&quot;&quot;<br>    n_samples: int<br>    window: int<br>    snr_db_low: float<br>    snr_db_high: float<br>    cfo_abs_max: float<br><br>def generate_raw_batch(out_dir: str, run_id: str, spec: BatchSpec) -&gt; tuple[str, str]:<br>    &quot;&quot;&quot;<br>    Generate a batch of synthetic IQ examples and write them to disk.<br><br>    Outputs:<br>      1) Parquet file containing per-sample rows with:<br>         - metadata: sample_id, run_id, modulation, snr_db, cfo, phi<br>         - waveform: I list and Q list (each of length = spec.window)<br>      2) JSON manifest describing the batch-level parameters.<br><br>    Returns:<br>      (parquet_path, manifest_path)<br>    &quot;&quot;&quot;<br>    # Ensure output folder exists.<br>    os.makedirs(out_dir, exist_ok=True)<br><br>    # Collect rows as Python dicts first, then convert to Arrow Table.<br>    rows = []<br><br>    # Generate spec.n_samples independent examples.<br>    for _ in range(spec.n_samples):<br>        # Randomly pick a modulation format for this example.<br>        mod = np.random.choice(MODS)<br><br>        # Get ideal constellation points for the selected modulation.<br>        const = _constellation(mod)<br><br>        # Sample a window-length sequence of random symbols from that constellation.<br>        sym = np.random.choice(const, size=spec.window)<br><br>        # Randomly choose channel/noise parameters for this example.<br>        snr_db = float(np.random.uniform(spec.snr_db_low, spec.snr_db_high))  # SNR in dB<br>        cfo = float(np.random.uniform(-spec.cfo_abs_max, spec.cfo_abs_max))   # CFO cycles/sample<br>        phi = float(np.random.uniform(-math.pi, math.pi))                     # constant phase offset<br><br>        # Apply deterministic impairments first: CFO then constant phase shift.<br>        y = _apply_phase(_apply_cfo(sym, cfo), phi)<br><br>        # Add AWGN to achieve the chosen SNR.<br>        y = _awgn(y, snr_db)<br><br>        # Unique ID so each row can be traced independently.<br>        sid = str(uuid.uuid4())<br><br>        # Store as a row-friendly format:<br>        # - Parquet/Arrow supports lists well<br>        # - Convert to float32 for compact storage<br>        # - Store I and Q separately as Python lists<br>        rows.append({<br>            &quot;sample_id&quot;: sid,<br>            &quot;run_id&quot;: run_id,<br>            &quot;modulation&quot;: mod,<br>            &quot;snr_db&quot;: snr_db,<br>            &quot;cfo&quot;: cfo,<br>            &quot;phi&quot;: phi,<br>            &quot;i&quot;: y.real.astype(np.float32).tolist(),<br>            &quot;q&quot;: y.imag.astype(np.float32).tolist(),<br>        })<br><br>    # Convert the list of dictionaries into a columnar Arrow table.<br>    table = pa.Table.from_pylist(rows)<br><br>    # Write the dataset to Parquet with zstd compression (good compression ratio + fast decode).<br>    parquet_path = os.path.join(out_dir, f&quot;raw_{run_id}.parquet&quot;)<br>    pq.write_table(table, parquet_path, compression=&quot;zstd&quot;)<br><br>    # Build a manifest describing the generation settings for reproducibility/debugging.<br>    manifest = {<br>        &quot;run_id&quot;: run_id,<br>        &quot;n_samples&quot;: spec.n_samples,<br>        &quot;window&quot;: spec.window,<br>        &quot;mods&quot;: MODS,<br>        &quot;snr_db_low&quot;: spec.snr_db_low,<br>        &quot;snr_db_high&quot;: spec.snr_db_high,<br>        &quot;cfo_abs_max&quot;: spec.cfo_abs_max,<br>    }<br><br>    # Write manifest to JSON (human-readable, easy to version and inspect).<br>    manifest_path = os.path.join(out_dir, f&quot;manifest_{run_id}.json&quot;)<br>    with open(manifest_path, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>        json.dump(manifest, f, indent=2)<br><br>    # Return paths so the caller can log them or pass them downstream.<br>    return parquet_path, manifest_path<br><br>def default_spec() -&gt; BatchSpec:<br>    &quot;&quot;&quot;<br>    Convenience helper to create a default BatchSpec from config constants.<br><br>    Defaults:<br>      - n_samples and window come from signalforge.config<br>      - SNR is sampled uniformly between 5 and 25 dB<br>      - CFO is sampled uniformly in [-0.02, 0.02] cycles/sample<br>    &quot;&quot;&quot;<br>    return BatchSpec(<br>        n_samples=SIGNALFORGE_N_SAMPLES,<br>        window=SIGNALFORGE_WINDOW,<br>        snr_db_low=5.0,<br>        snr_db_high=25.0,<br>        cfo_abs_max=0.02,<br>    )<br>EOF</pre><h3>Step 10: Feature extraction (shared by training and API)</h3><p>Now we implement one shared feature-extraction function that converts raw I/Q windows into a compact set of numeric features. This is a critical platform principle: training and inference must use the exact same feature logic. If feature extraction differs between the training pipeline and the production API (even slightly), your model can appear to work in training but silently degrade in production because it is no longer seeing the same input representation it was trained on.</p><h4>What this feature function does (high-level)</h4><p>Given one I/Q window (two numeric arrays), we build a small “feature vector” that summarizes the signal in a way a classical ML model can learn from. The features are intentionally lightweight and fast because they will run in both batch training and real-time inference.</p><p>The feature categories we compute:</p><p>1) Amplitude and power proxies</p><ul><li>A RMS-style magnitude feature computed from |x|², which acts as a stable amplitude/power summary.</li></ul><p>2) Dynamic range</p><ul><li>Peak-to-peak range of I and Q separately, which captures spread and clipping-like behavior.</li></ul><p>3) Distribution statistics (I and Q separately)</p><ul><li>Mean and standard deviation for basic location and scale.</li><li>Skewness and kurtosis to capture shape, asymmetry, and tail heaviness in the sample distribution.</li></ul><p>4) IQ balance proxy</p><ul><li>A simple imbalance metric derived from the difference between I and Q standard deviations. This helps capture hardware or channel effects that make I and Q behave differently.</li></ul><p>5) A simple spectral proxy</p><ul><li>A “spectral peak” measure derived from an FFT: max FFT magnitude relative to mean FFT magnitude. This is a crude but useful signal for whether there is a dominant tone or strong periodic structure versus more broadband content.</li></ul><h4>Sample</h4><p>Note: I’m using a tiny 8‑sample signal so it’s easy to read; the real pipeline uses 1024 samples.</p><p>Sample input</p><pre>import numpy as np<br>from signalforge.feature_extract import features_from_iq<br><br>i = np.array([1, 0, -1, 0, 1, 0, -1, 0], dtype=np.float32)<br>q = np.array([0, 1, 0, -1, 0, 1, 0, -1], dtype=np.float32)<br><br>features = features_from_iq(i, q)<br>print(features)</pre><p>Sample output (example values)</p><pre>{<br>  &quot;rms&quot;: 1.0,<br>  &quot;p2p_i&quot;: 2.0,<br>  &quot;p2p_q&quot;: 2.0,<br>  &quot;mean_i&quot;: 0.0,<br>  &quot;std_i&quot;: 0.7071,<br>  &quot;mean_q&quot;: 0.0,<br>  &quot;std_q&quot;: 0.7071,<br>  &quot;skew_i&quot;: 0.0,<br>  &quot;kurt_i&quot;: -2.0,<br>  &quot;skew_q&quot;: 0.0,<br>  &quot;kurt_q&quot;: -2.0,<br>  &quot;iq_imbalance&quot;: 0.0,<br>  &quot;fft_peak&quot;: 2.0<br>}</pre><h4>Implementation notes that matter</h4><ul><li>We build a complex baseband signal x = I + jQ internally for consistent computations.</li><li>We use a small epsilon to avoid divide-by-zero and edge-case instability.</li><li>The output is a flat dictionary of scalar features, which is convenient for storing as columns, feeding into scikit-learn, and logging as structured metadata.</li></ul><pre>cat &gt; src/signalforge/feature_extract.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import numpy as np<br>from scipy.stats import kurtosis, skew  # Statistical shape measures: skewness and kurtosis.<br><br>def features_from_iq(i: np.ndarray, q: np.ndarray) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Compute a small set of numeric features from I/Q samples.<br><br>    Inputs:<br>      i: in-phase samples (1D array)<br>      q: quadrature samples (1D array)<br><br>    Output:<br>      Dictionary of scalar features (floats) that summarize amplitude, distribution shape,<br>      simple IQ balance, and a crude spectral-peak measure.<br>    &quot;&quot;&quot;<br>    # Build complex baseband signal x[n] = I[n] + j Q[n] in float64 for stable stats/FFT.<br>    x = i.astype(np.float64) + 1j * q.astype(np.float64)<br><br>    # Magnitude squared per sample: |x|^2 = I^2 + Q^2 (used for power/RMS).<br>    mag2 = (i**2 + q**2).astype(np.float64)<br><br>    eps = 1e-12  # Small constant to avoid divide-by-zero / sqrt(0) edge cases.<br><br>    # RMS amplitude proxy: sqrt(mean(|x|^2)).<br>    rms = float(np.sqrt(np.mean(mag2) + eps))<br><br>    # Peak-to-peak ranges (dynamic range) on each axis.<br>    p2p_i = float(np.max(i) - np.min(i))<br>    p2p_q = float(np.max(q) - np.min(q))<br><br>    # Basic distribution stats for I and Q separately.<br>    mi, si = float(np.mean(i)), float(np.std(i) + eps)  # mean and std of I<br>    mq, sq = float(np.mean(q)), float(np.std(q) + eps)  # mean and std of Q<br><br>    # Skewness: asymmetry of the distribution; kurtosis: tail/peakedness measure.<br>    sk_i = float(skew(i))<br>    ku_i = float(kurtosis(i))<br>    sk_q = float(skew(q))<br>    ku_q = float(kurtosis(q))<br><br>    # Simple IQ imbalance proxy:<br>    # normalized difference between I and Q standard deviations (0 means equal spread).<br>    iq_imbalance = float(abs(si - sq) / (si + sq + eps))<br><br>    # &quot;Spectral peak&quot; proxy:<br>    # rFFT over complex x, then compare max FFT magnitude to mean FFT magnitude.<br>    # Higher value often indicates a strong tone/periodicity relative to broadband content.<br>    X = np.fft.rfft(x)<br>    fft_peak = float(np.max(np.abs(X)) / (np.mean(np.abs(X)) + eps))<br><br>    # Return a flat feature dict (easy to store as columns, feed to ML, etc.).<br>    return {<br>        &quot;rms&quot;: rms,<br>        &quot;p2p_i&quot;: p2p_i,<br>        &quot;p2p_q&quot;: p2p_q,<br>        &quot;mean_i&quot;: mi,<br>        &quot;std_i&quot;: si,<br>        &quot;mean_q&quot;: mq,<br>        &quot;std_q&quot;: sq,<br>        &quot;skew_i&quot;: sk_i,<br>        &quot;kurt_i&quot;: ku_i,<br>        &quot;skew_q&quot;: sk_q,<br>        &quot;kurt_q&quot;: ku_q,<br>        &quot;iq_imbalance&quot;: iq_imbalance,<br>        &quot;fft_peak&quot;: fft_peak,<br>    }<br>EOF</pre><p>In the future steps, both the training job and the FastAPI prediction path will call this same function, guaranteeing that “feature parity” holds across the entire system.</p><h3>Step 11: Enforce data quality and profiling</h3><p>We run schema checks and basic profiling before the pipeline proceeds.</p><p>Before we train anything or compute features, we add a validation gate. This prevents the classic “garbage in, garbage out” failure mode and demonstrates a core platform behavior: the pipeline should only advance when the data meets minimum trust criteria. We also generate a stored quality report so we can audit what happened in a given run and debug quickly when something breaks.</p><h4>What this quality step does (high level)</h4><p>We take the raw Parquet dataset produced by the generator and run two kinds of checks:</p><p><strong>1) Schema and value validation (hard correctness checks)</strong></p><p>Using a DataFrame schema validator, we confirm:</p><ul><li>Required columns exist and have expected types.</li><li>IDs are non-empty strings with reasonable length constraints.</li><li>The label (modulation) is one of the supported classes.</li><li>Numeric columns like SNR, CFO, and phase fall within broad sanity ranges (meant to catch corruption, not overfit the data).</li></ul><p><strong>2) Structural validation for IQ windows (hard fail gate)</strong></p><p>Because downstream feature extraction assumes a fixed window length, we explicitly verify that:</p><ul><li>Every row’s I array length equals the configured window size.</li><li>Every row’s Q array length equals the configured window size.</li></ul><p>If any row has the wrong length, we mark it as a hard failure and stop the pipeline from proceeding.</p><p>3) Lightweight profiling (observability for the dataset)</p><p>After validation, we compute simple statistical summaries grouped by modulation class, such as:</p><ul><li>count</li><li>mean, standard deviation</li><li>min and max</li></ul><p>for key numeric fields like SNR and CFO. This gives quick visibility into whether the dataset “looks right” and helps compare runs later (especially once we introduce drift).</p><p>4) Report generation for auditability</p><p>All results are written into a JSON report that includes:</p><ul><li>the dataset path and row count,</li><li>how many rows failed the I/Q window-length checks,</li><li>per-class profiling stats,</li><li>and a single hard_fail flag that determines whether the pipeline should stop.</li></ul><h4>Output and pipeline behavior</h4><p>The function returns a small result object that includes:</p><ul><li>ok: whether the dataset passed the hard validation gate</li><li>report_path: where the JSON report was written</li></ul><p>This makes it easy for Airflow to enforce a “quality gate” step: if ok is false, downstream tasks should not run, and the report becomes the primary artifact for debugging.</p><pre>cat &gt; src/signalforge/quality.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import json<br>from dataclasses import dataclass  # Used for a small immutable result object.<br>import numpy as np<br>import pandas as pd<br>import pyarrow.parquet as pq  # Reads the Parquet dataset produced by the generator.<br>import pandera as pa  # Data validation library for pandas DataFrames<br>from pandera import Column, DataFrameSchema, Check  # Schema definition helpers.<br><br>from signalforge.config import SIGNALFORGE_WINDOW  # Expected IQ window length for each sample.<br><br># Pandera schema that validates column presence/types and some value constraints.<br># strict=False means extra columns are allowed (useful if you add features later).<br>SCHEMA = DataFrameSchema(<br>    {<br>        # IDs should be non-empty strings within reasonable length bounds.<br>        &quot;sample_id&quot;: Column(str, Check.str_length(10, 200)),<br>        &quot;run_id&quot;: Column(str, Check.str_length(5, 200)),<br><br>        # Modulation must be one of the known classes.<br>        &quot;modulation&quot;: Column(str, Check.isin([&quot;BPSK&quot;, &quot;QPSK&quot;, &quot;16QAM&quot;, &quot;64QAM&quot;])),<br><br>        # Numeric sanity ranges (broad, meant to catch corrupted data).<br>        &quot;snr_db&quot;: Column(float, Check.in_range(-5, 60)),<br>        &quot;cfo&quot;: Column(float, Check.in_range(-1, 1)),<br>        &quot;phi&quot;: Column(float, Check.in_range(-10, 10)),<br><br>        # i and q are stored as arrays/lists in Parquet; in pandas they show up as dtype=object.<br>        &quot;i&quot;: Column(object),<br>        &quot;q&quot;: Column(object),<br>    },<br>    strict=False,<br>)<br><br>@dataclass(frozen=True)<br>class QualityResult:<br>    &quot;&quot;&quot;<br>    Result returned by the quality check run.<br>    ok: whether the dataset passed the &quot;hard fail&quot; checks<br>    report_path: where the JSON report was written<br>    &quot;&quot;&quot;<br>    ok: bool<br>    report_path: str<br><br>def _check_window_len(arr, expected: int) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Return True if arr is a list-like of exactly the expected length.<br>    This is a defensive check for the IQ arrays.<br>    &quot;&quot;&quot;<br>    if arr is None:<br>        return False<br>    if isinstance(arr, list):<br>        return len(arr) == expected<br>    if isinstance(arr, np.ndarray):<br>        return arr.ndim == 1 and arr.shape[0] == expected<br>    if hasattr(arr, &quot;as_py&quot;):<br>        try:<br>            return len(arr.as_py()) == expected<br>        except Exception:<br>            return False<br>    if hasattr(arr, &quot;__len__&quot;):<br>        try:<br>            return len(arr) == expected<br>        except TypeError:<br>            return False<br>    return False<br><br>def run_quality_checks(raw_parquet_path: str, out_report_path: str) -&gt; QualityResult:<br>    &quot;&quot;&quot;<br>    Run basic validation and profiling on the raw IQ dataset.<br><br>    Steps:<br>      1) Load Parquet -&gt; Arrow table -&gt; pandas DataFrame<br>      2) Validate schema + value ranges with Pandera<br>      3) Validate IQ array lengths match SIGNALFORGE_WINDOW<br>      4) Compute simple per-modulation stats (count/mean/std/min/max)<br>      5) Write a JSON report and return pass/fail status<br>    &quot;&quot;&quot;<br>    # Load the Parquet file produced by the generator.<br>    table = pq.read_table(raw_parquet_path)<br><br>    # Convert to pandas for Pandera validation and groupby profiling.<br>    df = table.to_pandas()<br><br>    # Basic schema checks (types, required columns, value constraints).<br>    # lazy=True collects all schema errors before raising (more useful than failing fast).<br>    SCHEMA.validate(df, lazy=True)<br><br>    # Array length checks:<br>    # Count rows where &quot;i&quot; or &quot;q&quot; is not a list of the expected window length.<br>    bad_i = df[&quot;i&quot;].apply(lambda x: not _check_window_len(x, SIGNALFORGE_WINDOW)).sum()<br>    bad_q = df[&quot;q&quot;].apply(lambda x: not _check_window_len(x, SIGNALFORGE_WINDOW)).sum()<br><br>    # Basic statistical profiling by modulation:<br>    # For each modulation, compute aggregate stats for snr_db and cfo.<br>    prof_df = df.groupby(&quot;modulation&quot;)[[&quot;snr_db&quot;, &quot;cfo&quot;]].agg(<br>        [&quot;count&quot;, &quot;mean&quot;, &quot;std&quot;, &quot;min&quot;, &quot;max&quot;]<br>    )<br>    prof_df.columns = [f&quot;{col}_{stat}&quot; for col, stat in prof_df.columns]<br>    prof = prof_df.to_dict(orient=&quot;index&quot;)<br><br>    # Build a report that can be stored as an artifact in CI or a pipeline run.<br>    report = {<br>        &quot;raw_path&quot;: raw_parquet_path,<br>        &quot;rows&quot;: int(df.shape[0]),<br>        &quot;bad_i_window&quot;: int(bad_i),<br>        &quot;bad_q_window&quot;: int(bad_q),<br>        &quot;profile&quot;: prof,<br>        # Treat any window-length mismatch as a &quot;hard fail&quot; because downstream code assumes fixed length.<br>        &quot;hard_fail&quot;: bool(bad_i &gt; 0 or bad_q &gt; 0),<br>    }<br><br>    # Write report to disk as pretty-printed JSON.<br>    with open(out_report_path, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>        json.dump(report, f, indent=2)<br><br>    # ok=True only if we did not trigger a hard failure.<br>    return QualityResult(ok=not report[&quot;hard_fail&quot;], report_path=out_report_path)<br>EOF</pre><h3>Step 12: Spark feature engineering job</h3><p>In this step, we move feature engineering into Spark so the transformation is scalable and repeatable. Conceptually, the job does three things: it reads raw, versioned I/Q data from lakeFS, computes the same standardized numeric features for every window using distributed compute, and writes the resulting feature table back to the versioned lake as Parquet. This keeps the entire “raw → features” transformation reproducible and traceable across branches and commits.</p><h4>Why we do this in Spark</h4><p>Even though our dataset is synthetic and small during development, the platform design should work for real workloads. Spark gives us:</p><ul><li>distributed execution for heavy transformations,</li><li>consistent Parquet output optimized for downstream ML,</li><li>and a clean separation between “raw storage” and “curated features” as a first-class dataset.</li></ul><h4>Feature logic (still shared, just executed at scale)</h4><p>The feature extraction used by Spark is the same logic we use elsewhere (training and inference). The function converts each I/Q window into a compact set of scalar features, including:</p><ul><li>amplitude and power proxies (RMS derived from |x|²),</li><li>dynamic range (peak-to-peak I and Q),</li><li>distribution statistics (mean, standard deviation, skewness, kurtosis for I and Q),</li><li>an IQ imbalance proxy (difference between I and Q spread),</li><li>and a simple spectral proxy (FFT peak relative to average magnitude).</li></ul><h4>The important platform point:</h4><p>Feature parity must hold across the stack. Whether features are computed in Spark (batch) or inside the API (online inference), the same mathematical definition must be used to avoid training-serving skew.</p><h4>What comes next</h4><p>Once this job is wired into the pipeline, we will treat the feature Parquet output as a curated dataset: versioned, reproducible, and ready for training, drift checks, and model serving.</p><pre>cat &gt; spark_jobs/feature_engineering.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import numpy as np<br>from scipy.stats import kurtosis, skew  # Statistical shape measures: skewness and kurtosis.<br><br>def features_from_iq(i: np.ndarray, q: np.ndarray) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Compute a small set of numeric features from I/Q samples.<br><br>    Inputs:<br>      i: in-phase samples (1D array)<br>      q: quadrature samples (1D array)<br><br>    Output:<br>      Dictionary of scalar features (floats) that summarize amplitude, distribution shape,<br>      simple IQ balance, and a crude spectral-peak measure.<br>    &quot;&quot;&quot;<br>    # Build complex baseband signal x[n] = I[n] + j Q[n] in float64 for stable stats/FFT.<br>    x = i.astype(np.float64) + 1j * q.astype(np.float64)<br><br>    # Magnitude squared per sample: |x|^2 = I^2 + Q^2 (used for power/RMS).<br>    mag2 = (i**2 + q**2).astype(np.float64)<br><br>    eps = 1e-12  # Small constant to avoid divide-by-zero / sqrt(0) edge cases.<br><br>    # RMS amplitude proxy: sqrt(mean(|x|^2)).<br>    rms = float(np.sqrt(np.mean(mag2) + eps))<br><br>    # Peak-to-peak ranges (dynamic range) on each axis.<br>    p2p_i = float(np.max(i) - np.min(i))<br>    p2p_q = float(np.max(q) - np.min(q))<br><br>    # Basic distribution stats for I and Q separately.<br>    mi, si = float(np.mean(i)), float(np.std(i) + eps)  # mean and std of I<br>    mq, sq = float(np.mean(q)), float(np.std(q) + eps)  # mean and std of Q<br><br>    # Skewness: asymmetry of the distribution; kurtosis: tail/peakedness measure.<br>    sk_i = float(skew(i))<br>    ku_i = float(kurtosis(i))<br>    sk_q = float(skew(q))<br>    ku_q = float(kurtosis(q))<br><br>    # Simple IQ imbalance proxy:<br>    # normalized difference between I and Q standard deviations (0 means equal spread).<br>    iq_imbalance = float(abs(si - sq) / (si + sq + eps))<br><br>    # &quot;Spectral peak&quot; proxy:<br>    # rFFT over complex x, then compare max FFT magnitude to mean FFT magnitude.<br>    # Higher value often indicates a strong tone/periodicity relative to broadband content.<br>    X = np.fft.rfft(x)<br>    fft_peak = float(np.max(np.abs(X)) / (np.mean(np.abs(X)) + eps))<br><br>    # Return a flat feature dict (easy to store as columns, feed to ML, etc.).<br>    return {<br>        &quot;rms&quot;: rms,<br>        &quot;p2p_i&quot;: p2p_i,<br>        &quot;p2p_q&quot;: p2p_q,<br>        &quot;mean_i&quot;: mi,<br>        &quot;std_i&quot;: si,<br>        &quot;mean_q&quot;: mq,<br>        &quot;std_q&quot;: sq,<br>        &quot;skew_i&quot;: sk_i,<br>        &quot;kurt_i&quot;: ku_i,<br>        &quot;skew_q&quot;: sk_q,<br>        &quot;kurt_q&quot;: ku_q,<br>        &quot;iq_imbalance&quot;: iq_imbalance,<br>        &quot;fft_peak&quot;: fft_peak,<br>    }<br>EOF</pre><h3>Step 13: Training + MLflow registry</h3><p>This step demonstrates the MLOps layer of the platform: repeatable training, experiment tracking, and a controlled model lifecycle. We train a model on the engineered feature dataset, log all key details to MLflow (metrics, parameters, and lineage), register the resulting model in the MLflow Model Registry, and then promote the newest “good” version to Production.</p><h4>Why this matters in a platform context</h4><p>Training a model is not the hard part. The hard part is making training reproducible, debuggable, and safe to deploy. This step shows the basics of production-style model governance:</p><ul><li>Every model run is tracked,</li><li>Every model can be traced back to the exact data version that produced it,</li><li>And only one model version is marked as Production at a time (with older versions archived, not deleted).</li></ul><h4>What the training module does (high level)</h4><p><strong>1) Wait for MLflow and configure the experiment</strong></p><p>Before training starts, we ensure the MLflow tracking server is reachable. Then we set a consistent experiment name so all runs land in one place in the MLflow UI.</p><p><strong>2) Load the feature dataset from lakeFS (version-aware)</strong></p><p>The engineered features live inside lakeFS and are accessed through the lakeFS S3 gateway. This is important because:</p><ul><li>We are reading data from a specific branch and run_id, which makes the training input reproducible,</li><li>and Spark typically writes Parquet as a directory of multiple “part” files rather than a single file.</li></ul><p>To handle that, the training code downloads all objects under the Spark output prefix into a temporary local directory, filters out non-data artifacts (hidden files, success markers, checksum files), reads the valid Parquet parts, and concatenates them into one pandas DataFrame for training.</p><p><strong>3) Build X/y consistently</strong></p><p>We define the exact list of expected feature columns and extract:</p><ul><li>X: the feature matrix (cast to numeric types)</li><li>y: the target label (modulation class)</li></ul><p><strong>4) Split, train, and evaluate</strong></p><p>We do a stratified train/test split so class balance is preserved in both splits. Then we train a baseline RandomForest classifier and compute accuracy on the held-out test set. The model choice is intentionally simple; the focus here is on the platform lifecycle around it.</p><p><strong>5) Log everything to MLflow (tracking + lineage)</strong></p><p>Inside an MLflow run, we log:</p><ul><li>parameters (model type, key hyperparameters),</li><li>metrics (accuracy),</li><li>and lineage tags (lakeFS repo, lakeFS branch, and run_id).</li></ul><p>These tags are what make the system traceable: you can answer <strong>“which dataset version produced this model?”</strong> later, without guessing.</p><p><strong>6) Register and promote the model in the registry</strong></p><p>We log the trained model artifact to MLflow and register it under a stable name (for example, rf_modulation_classifier). That creates a new model version. Then we implement a simple governance rule:</p><ul><li>archive any model versions currently in Production,</li><li>promote the latest created version to Production,</li></ul><p>So the serving layer can always load “Production” without needing to know the numeric version.</p><h4>Outputs</h4><p>The function returns a compact dictionary with:</p><ul><li>the MLflow run id (for traceability),</li><li>the accuracy metric,</li><li>and the model version promoted to Production.</li></ul><p>These values are useful for pipeline logs, notifications, and later drift monitoring comparisons.</p><pre>cat &gt; src/signalforge/train.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import os  # Filesystem utilities for paths and filtering Spark-written files.<br>import tempfile  # Used to create a temporary directory for downloaded parquet parts.<br>import time<br>import numpy as np  <br>import pandas as pd  # Used to read parquet parts and build a single training DataFrame.<br>import mlflow  # Experiment tracking + model logging/registration.<br>from mlflow.tracking import MlflowClient  # Used for model registry operations (staging transitions).<br>from sklearn.model_selection import train_test_split  # Train/test split with stratification.<br>from sklearn.metrics import accuracy_score  # Simple classification metric.<br>from sklearn.ensemble import RandomForestClassifier  # Baseline model for modulation classification.<br>import requests<br><br>from signalforge.config import MLFLOW_TRACKING_URI  # Where MLflow tracking server is reachable.<br>from signalforge.lakefs_ops import LakeFSContext, lakefs_s3_client  # lakeFS context + S3 gateway client.<br><br># Feature columns expected in the features parquet produced by the Spark featurization job.<br>FEATURE_COLS = [<br>    &quot;rms&quot;,&quot;p2p_i&quot;,&quot;p2p_q&quot;,&quot;mean_i&quot;,&quot;std_i&quot;,&quot;mean_q&quot;,&quot;std_q&quot;,<br>    &quot;skew_i&quot;,&quot;kurt_i&quot;,&quot;skew_q&quot;,&quot;kurt_q&quot;,&quot;iq_imbalance&quot;,&quot;fft_peak&quot;,<br>]<br><br>def _download_prefix_to_dir(s3, bucket: str, prefix: str, out_dir: str) -&gt; list[str]:<br>    &quot;&quot;&quot;<br>    Download all objects under a given S3 prefix into a local directory.<br><br>    Notes:<br>      - This uses list_objects_v2 (single page). If there are many objects, pagination may be needed.<br>      - It flattens S3 keys into filenames by replacing &quot;/&quot; with &quot;_&quot; to avoid creating nested dirs.<br>    &quot;&quot;&quot;<br>    resp = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)  # List objects that start with prefix.<br>    if &quot;Contents&quot; not in resp:<br>        return []  # No objects found for that prefix.<br><br>    files = []<br>    for obj in resp[&quot;Contents&quot;]:<br>        key = obj[&quot;Key&quot;]  # Full object key in the bucket.<br><br>        # Skip &quot;directory marker&quot; keys if present.<br>        if key.endswith(&quot;/&quot;):<br>            continue<br><br>        # Map S3 key -&gt; local file path.<br>        local = os.path.join(out_dir, key.replace(&quot;/&quot;, &quot;_&quot;))<br><br>        # Ensure local parent directory exists (mostly redundant due to flattening, but safe).<br>        os.makedirs(os.path.dirname(local), exist_ok=True)<br><br>        # Download object to local filesystem.<br>        s3.download_file(bucket, key, local)<br>        files.append(local)<br><br>    return files  # Return list of local file paths.<br><br>def wait_for_mlflow(tracking_uri: str, timeout_s: int = 300) -&gt; None:<br>    &quot;&quot;&quot;<br>    Wait for the MLflow tracking server to respond before continuing.<br>    &quot;&quot;&quot;<br>    url = tracking_uri.rstrip(&quot;/&quot;) + &quot;/&quot;<br>    deadline = time.time() + timeout_s<br>    last_err = None<br>    while time.time() &lt; deadline:<br>        try:<br>            r = requests.get(url, timeout=3)<br>            if r.status_code in (200, 302, 401, 403):<br>                return<br>        except Exception as e:<br>            last_err = e<br>        time.sleep(2)<br>    raise RuntimeError(f&quot;MLflow not reachable at {url}. last_err={last_err!r}&quot;)<br><br>def load_features_df(ctx: LakeFSContext, branch: str, run_id: str) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Load the engineered feature dataset for a given (branch, run_id) from lakeFS via its S3 gateway.<br><br>    Why this is needed:<br>      Spark typically writes Parquet as a directory with multiple part files, not a single file.<br>      This function downloads all relevant parts and concatenates them into one pandas DataFrame.<br>    &quot;&quot;&quot;<br>    s3 = lakefs_s3_client(ctx)  # S3 client configured for lakeFS gateway.<br>    bucket = ctx.repo           # In lakeFS S3 gateway, repo name acts like the bucket.<br><br>    # Prefix where Spark wrote the Parquet outputs.<br>    # Note: This looks like a &quot;file&quot;, but Spark often stores a directory-like prefix containing part files.<br>    prefix = f&quot;{branch}/features/{run_id}/features.parquet&quot;<br><br>    # Use a temp directory so downloaded parts are cleaned up automatically.<br>    with tempfile.TemporaryDirectory() as td:<br>        files = _download_prefix_to_dir(s3, bucket, prefix, td)<br>        if not files:<br>            raise RuntimeError(&quot;No feature parquet found at prefix: &quot; + prefix)<br><br>        # Spark writes multiple part files; read as many valid parquet parts as we can.<br>        parts = []<br>        for f in files:<br>            # Skip checksum files that Spark/Hadoop sometimes writes.<br>            if f.endswith(&quot;.crc&quot;):<br>                continue<br><br>            # Skip hidden/system files like _SUCCESS, _committed_, ._metadata, etc.<br>            if os.path.basename(f).startswith(&quot;_&quot;) or os.path.basename(f).startswith(&quot;.&quot;):<br>                continue<br><br>            # Try reading parquet; ignore failures (defensive against non-parquet artifacts).<br>            try:<br>                parts.append(pd.read_parquet(f))<br>            except Exception:<br>                pass<br><br>        if not parts:<br>            raise RuntimeError(&quot;Could not read any parquet parts&quot;)<br><br>        # Combine all part DataFrames into one DataFrame.<br>        return pd.concat(parts, ignore_index=True)<br><br>def train_and_register(<br>    ctx: LakeFSContext,<br>    branch: str,<br>    run_id: str,<br>    model_name: str = &quot;rf_modulation_classifier&quot;,<br>) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Train a RandomForest classifier on engineered features and register it in MLflow Model Registry.<br><br>    Steps:<br>      1) Point MLflow to the configured tracking server and choose an experiment<br>      2) Load features from lakeFS for the given run<br>      3) Split into train/test (stratified by modulation class)<br>      4) Train model, compute accuracy, log params/metrics/tags<br>      5) Log and register the model under `model_name`<br>      6) Promote latest version to Production and archive any existing Production versions<br>      7) Return run_id, accuracy, and model version for downstream pipeline steps<br>    &quot;&quot;&quot;<br>    # Configure MLflow tracking backend.<br>    mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)<br><br>    # Ensure runs are grouped under this experiment name in MLflow UI.<br>    wait_for_mlflow(MLFLOW_TRACKING_URI)<br>    mlflow.set_experiment(&quot;signalforge_modulation&quot;)<br><br>    # Load feature dataset from lakeFS branch/run-id.<br>    df = load_features_df(ctx, branch, run_id)<br><br>    # Build feature matrix X and label vector y.<br>    X = df[FEATURE_COLS].astype(float)<br>    y = df[&quot;modulation&quot;].astype(str)<br><br>    # Train/test split with stratify=y to preserve class distribution in both splits.<br>    X_train, X_test, y_train, y_test = train_test_split(<br>        X, y,<br>        test_size=0.2,<br>        random_state=7,<br>        stratify=y,<br>    )<br><br>    # Start an MLflow run so all logs/artifacts are attached to a single run record.<br>    with mlflow.start_run(run_name=f&quot;train_{run_id}&quot;) as run:<br>        # Define the classifier.<br>        clf = RandomForestClassifier(<br>            n_estimators=250,  # Number of trees in the forest.<br>            max_depth=None,    # Let trees expand until pure or until other stopping rules apply.<br>            random_state=7,    # Reproducibility for bootstrap sampling / splits in trees.<br>            n_jobs=-1,         # Use all available CPU cores.<br>        )<br><br>        # Train on the training split.<br>        clf.fit(X_train, y_train)<br><br>        # Evaluate on the held-out test split.<br>        pred = clf.predict(X_test)<br>        acc = float(accuracy_score(y_test, pred))<br><br>        # Log training configuration and evaluation metrics to MLflow.<br>        mlflow.log_param(&quot;model_type&quot;, &quot;RandomForestClassifier&quot;)<br>        mlflow.log_param(&quot;n_estimators&quot;, 250)<br>        mlflow.log_metric(&quot;accuracy&quot;, acc)<br><br>        # Add lineage tags so you can trace which lakeFS data produced this model.<br>        mlflow.set_tag(&quot;lakefs_repo&quot;, ctx.repo)<br>        mlflow.set_tag(&quot;lakefs_branch&quot;, branch)<br>        mlflow.set_tag(&quot;run_id&quot;, run_id)<br><br>        # Log the sklearn model artifact and register it under the given registry name.<br>        # This typically creates a new model version in the MLflow Model Registry.<br>        mlflow.sklearn.log_model(<br>            clf,<br>            artifact_path=&quot;model&quot;,<br>            registered_model_name=model_name,<br>        )<br><br>        client = MlflowClient()<br><br>        # Find the latest registered version for this model name.<br>        # search_model_versions returns a list of version objects, version is a string.<br>        versions = client.search_model_versions(f&quot;name=&#39;{model_name}&#39;&quot;)<br>        latest = max(versions, key=lambda v: int(v.version))<br><br>        # Promote the latest version to &quot;Production&quot;.<br>        # First, archive any versions currently marked as Production (so there&#39;s only one).<br>        current_prod = client.get_latest_versions(model_name, stages=[&quot;Production&quot;])<br>        for v in current_prod:<br>            client.transition_model_version_stage(model_name, v.version, stage=&quot;Archived&quot;)<br><br>        # Move the newly created latest version into Production.<br>        client.transition_model_version_stage(model_name, latest.version, stage=&quot;Production&quot;)<br><br>        # Return key outputs for pipeline logging or notifications.<br>        return {<br>            &quot;mlflow_run_id&quot;: run.info.run_id,<br>            &quot;accuracy&quot;: acc,<br>            &quot;model_version&quot;: latest.version,<br>        }<br>EOF</pre><h3>Step 14: Drift detection + rollback hook</h3><p>This step adds a “safety loop” to the platform. When new data arrives, we compare it against a reference (baseline) dataset, quantify how much the distribution has shifted, publish that drift signal into monitoring, and if the drift is too high, automatically roll back the MLflow Production model to a previous stable version. The intent is simple: reduce operational risk when real-world data changes.</p><h4>Why this matters</h4><p>In real systems, data rarely stays stable. Hardware changes, environment changes, signal conditions change, and suddenly the model that looked good yesterday can degrade today. A platform should not only train and deploy models, it should also detect when assumptions break and respond safely. This step demonstrates that “production mindset” in a minimal form.</p><h4>What the drift module does (high-level)</h4><p><strong>1) Load baseline and current features from lakeFS</strong></p><p>We read engineered feature datasets from the versioned lake (lakeFS) using its S3 gateway. Just like training, we handle Spark-style Parquet outputs that are stored as multiple part files under a prefix. The drift check pulls:</p><ul><li>a baseline feature dataset identified by (baseline branch, baseline run_id)</li><li>a current feature dataset identified by (current branch, current run_id)</li></ul><p>There is also a defensive fallback: if the baseline is not found on the chosen branch, the code can fall back to main for the baseline run.</p><p><strong>2) Compute drift as “share of drifted feature columns.”</strong></p><p>To keep drift detection lightweight and explainable, we use PSI (Population Stability Index) per feature column:</p><ul><li>For each feature, PSI is computed by comparing the baseline distribution to the current distribution using bins derived from baseline quantiles.</li><li>A feature is considered “drifted” if PSI crosses a heuristic threshold (commonly 0.2).</li><li>drift_share is then computed as:<br> (Number of Drifted Feature Columns) / (total feature columns)</li></ul><p>This gives one simple number that answers: “How much of our feature space has shifted?”</p><p><strong>3) Push drift metrics to monitoring via Pushgateway</strong></p><p>Drift checks often run as batch jobs (not continuously scraped services). For that reason, we push the drift result to Pushgateway, and Prometheus then scrapes it. This makes drift visible in Grafana alongside normal service metrics, and it becomes easy to alert on it later.</p><p><strong>4) Roll back the model if the drift is too high</strong></p><p>If drift_share exceeds the configured drift threshold:</p><ul><li>we connect to MLflow Model Registry,</li><li>identify the current Production model version,</li><li>identify the latest Archived version available to restore,</li><li>archive the current Production version,</li><li>and promote the chosen Archived version back to Production.</li></ul><p>If drift is below threshold, or if registry state does not allow rollback (no Production model, or no Archived version), we return a clear “no action” reason instead of failing silently.</p><h4>Outputs</h4><p>The drift check returns a structured result that includes:</p><ul><li>drift_share (the computed drift level)</li><li>rollback status (whether rollback happened, and if so, from which version to which version)</li></ul><p>This structure is useful for Airflow logs, notifications, and incident-style debugging.</p><pre>cat &gt; src/signalforge/drift.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import os<br>import tempfile<br>from typing import Dict, List<br><br>from signalforge.lakefs_ops import LakeFSContext, lakefs_s3_client<br><br><br>PUSHGATEWAY_URL = os.getenv(&quot;PUSHGATEWAY_URL&quot;, &quot;http://pushgateway:9091&quot;).rstrip(&quot;/&quot;)<br>MLFLOW_TRACKING_URI = os.getenv(&quot;MLFLOW_TRACKING_URI&quot;, &quot;&quot;)<br>SIGNALFORGE_DRIFT_THRESHOLD = float(os.getenv(&quot;SIGNALFORGE_DRIFT_THRESHOLD&quot;, &quot;0.3&quot;))<br><br><br>def _download_prefix_to_dir(s3, bucket: str, prefix: str, local_dir: str) -&gt; List[str]:<br>    &quot;&quot;&quot;<br>    Download all objects under prefix into local_dir.<br>    Returns list of local file paths.<br>    &quot;&quot;&quot;<br>    import os<br><br>    paths: List[str] = []<br>    token = None<br><br>    while True:<br>        kwargs = {&quot;Bucket&quot;: bucket, &quot;Prefix&quot;: prefix}<br>        if token:<br>            kwargs[&quot;ContinuationToken&quot;] = token<br><br>        resp = s3.list_objects_v2(**kwargs)<br>        for obj in resp.get(&quot;Contents&quot;, []):<br>            key = obj[&quot;Key&quot;]<br>            if key.endswith(&quot;/&quot;) or key.endswith(&quot;.crc&quot;):<br>                continue<br>            name = os.path.basename(key)<br>            if name.startswith(&quot;_&quot;) or name.startswith(&quot;.&quot;):<br>                continue<br><br>            local_path = os.path.join(local_dir, name)<br>            s3.download_file(bucket, key, local_path)<br>            paths.append(local_path)<br><br>        if not resp.get(&quot;IsTruncated&quot;):<br>            break<br>        token = resp.get(&quot;NextContinuationToken&quot;)<br><br>    return paths<br><br><br>def _load_features(ctx: LakeFSContext, branch: str, run_id: str):<br>    &quot;&quot;&quot;<br>    Read parquet parts for: {branch}/features/{run_id}/features.parquet<br>    &quot;&quot;&quot;<br>    import pandas as pd<br><br>    s3 = lakefs_s3_client(ctx)<br>    bucket = ctx.repo<br>    prefix = f&quot;{branch}/features/{run_id}/features.parquet&quot;<br><br>    with tempfile.TemporaryDirectory() as td:<br>        files = _download_prefix_to_dir(s3, bucket, prefix, td)<br>        if not files:<br>            raise RuntimeError(f&quot;No feature files found at s3://{bucket}/{prefix}&quot;)<br><br>        dfs = []<br>        for f in files:<br>            try:<br>                dfs.append(pd.read_parquet(f))<br>            except Exception:<br>                continue<br><br>        if not dfs:<br>            raise RuntimeError(f&quot;No readable parquet parts for run_id={run_id}&quot;)<br><br>        return pd.concat(dfs, ignore_index=True)<br><br><br>def _psi(ref, cur, bins: int = 10, eps: float = 1e-6) -&gt; float:<br>    &quot;&quot;&quot;<br>    Population Stability Index for a single feature.<br>    &quot;&quot;&quot;<br>    import numpy as np<br><br>    ref = np.asarray(ref, dtype=float)<br>    cur = np.asarray(cur, dtype=float)<br><br>    ref = ref[np.isfinite(ref)]<br>    cur = cur[np.isfinite(cur)]<br><br>    if ref.size &lt; 50 or cur.size &lt; 50:<br>        return 0.0<br><br>    qs = np.quantile(ref, np.linspace(0, 1, bins + 1))<br>    qs[0] = -np.inf<br>    qs[-1] = np.inf<br><br>    ref_hist, _ = np.histogram(ref, bins=qs)<br>    cur_hist, _ = np.histogram(cur, bins=qs)<br><br>    ref_p = ref_hist / max(ref_hist.sum(), 1)<br>    cur_p = cur_hist / max(cur_hist.sum(), 1)<br><br>    ref_p = np.clip(ref_p, eps, 1.0)<br>    cur_p = np.clip(cur_p, eps, 1.0)<br><br>    return float(((cur_p - ref_p) * np.log(cur_p / ref_p)).sum())<br><br><br>def compute_drift_share(ref_df, cur_df, feature_cols: List[str]) -&gt; float:<br>    &quot;&quot;&quot;<br>    A column is considered drifted if PSI &gt; 0.2 (common PSI heuristic).<br>    drift_share = (# drifted cols) / (# cols)<br>    &quot;&quot;&quot;<br>    drifted = 0<br>    total = len(feature_cols)<br><br>    for c in feature_cols:<br>        score = _psi(ref_df[c].values, cur_df[c].values)<br>        if score &gt; 0.2:<br>            drifted += 1<br><br>    return float(drifted / total) if total else 0.0<br><br><br>def push_drift_metric(run_id: str, drift_share: float) -&gt; None:<br>    import requests<br><br>    job = &quot;signalforge_drift&quot;<br>    url = f&quot;{PUSHGATEWAY_URL}/metrics/job/{job}&quot;<br>    payload = f&#39;signalforge_drift_share{{run_id=&quot;{run_id}&quot;}} {drift_share}\n&#39;<br>    r = requests.post(url, data=payload.encode(&quot;utf-8&quot;), timeout=10)<br>    r.raise_for_status()<br><br><br>def rollback_if_needed(model_name: str, drift_share: float) -&gt; Dict:<br>    &quot;&quot;&quot;<br>    If drift_share exceeds threshold, rollback Production model to latest Archived.<br>    &quot;&quot;&quot;<br>    if not MLFLOW_TRACKING_URI:<br>        return {&quot;action&quot;: &quot;none&quot;, &quot;reason&quot;: &quot;mlflow_tracking_uri_not_set&quot;}<br><br>    if drift_share &lt;= SIGNALFORGE_DRIFT_THRESHOLD:<br>        return {&quot;action&quot;: &quot;none&quot;, &quot;reason&quot;: &quot;drift_below_threshold&quot;, &quot;drift_share&quot;: drift_share}<br><br>    import mlflow<br>    from mlflow.tracking import MlflowClient<br><br>    mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)<br>    client = MlflowClient()<br><br>    prod = client.get_latest_versions(model_name, stages=[&quot;Production&quot;])<br>    if not prod:<br>        return {&quot;action&quot;: &quot;none&quot;, &quot;reason&quot;: &quot;no_production_model&quot;, &quot;drift_share&quot;: drift_share}<br><br>    archived = client.get_latest_versions(model_name, stages=[&quot;Archived&quot;])<br>    if not archived:<br>        return {&quot;action&quot;: &quot;none&quot;, &quot;reason&quot;: &quot;no_archived_version_to_restore&quot;, &quot;drift_share&quot;: drift_share}<br><br>    cur_prod = prod[0]<br>    restore = max(archived, key=lambda v: int(v.version))<br><br>    client.transition_model_version_stage(model_name, cur_prod.version, stage=&quot;Archived&quot;)<br>    client.transition_model_version_stage(model_name, restore.version, stage=&quot;Production&quot;)<br><br>    return {&quot;action&quot;: &quot;rollback&quot;, &quot;from_version&quot;: cur_prod.version, &quot;to_version&quot;: restore.version, &quot;drift_share&quot;: drift_share}<br><br><br>def drift_check(<br>    ctx: LakeFSContext,<br>    branch: str,<br>    baseline_run_id: str,<br>    current_run_id: str,<br>    model_name: str,<br>    baseline_branch: str | None = None,<br>) -&gt; Dict:<br>    &quot;&quot;&quot;<br>    End-to-end drift check:<br>      1) load baseline + current features from lakeFS<br>      2) compute drift_share<br>      3) push metric<br>      4) rollback if needed<br>    &quot;&quot;&quot;<br>    # Import feature list lazily to avoid DAG import costs<br>    from signalforge.train import FEATURE_COLS<br><br>    base_branch = baseline_branch or branch<br>    try:<br>        ref_df = _load_features(ctx, base_branch, baseline_run_id)<br>    except RuntimeError:<br>        if base_branch != &quot;main&quot;:<br>            ref_df = _load_features(ctx, &quot;main&quot;, baseline_run_id)<br>        else:<br>            raise<br>    cur_df = _load_features(ctx, branch, current_run_id)<br><br>    drift_share = compute_drift_share(ref_df, cur_df, FEATURE_COLS)<br><br>    push_drift_metric(current_run_id, drift_share)<br>    rb = rollback_if_needed(model_name, drift_share)<br><br>    return {&quot;drift_share&quot;: drift_share, &quot;rollback&quot;: rb}<br>EOF</pre><h3>Step 15: FastAPI service</h3><p>In this step, we build the “self-serve” interface of the platform: a FastAPI service that other teams can call without needing to understand the underlying lake, orchestration, or model registry internals. The service loads the MLflow Model Registry’s Production model, exposes a /predict endpoint for inference, and publishes Prometheus metrics (request count and latency), so it is observable from day one.</p><h4>Why this matters in a platform context</h4><p>Platform work is not only about pipelines. It is also about packaging capabilities behind stable, internal APIs that are safe, measurable, and easy to consume. This service is the bridge between our MLOps layer (MLflow registry) and downstream product usage (real-time predictions).</p><h4>What the API does (high-level)</h4><p><strong>1) Centralized configuration via environment variables</strong></p><p>The service is configured using env vars, so it works cleanly inside Docker Compose:</p><ul><li>where MLflow is reachable (tracking URI),</li><li>the registered model name,</li><li>and which stage to load (Production by default).</li></ul><p><strong>2) Model loading from MLflow Model Registry (Production stage)</strong></p><p>On startup, the API attempts to load:<br>models:/&lt;MODEL_NAME&gt;/&lt;MODEL_STAGE&gt;</p><p>Key operational behavior:</p><ul><li>If the model exists and MLflow is reachable, the model is loaded once and kept in memory for fast predictions.</li><li>If the model is not registered yet, the API does not crash. It starts in a “degraded but alive” mode, so you can still use /health and /model for debugging. In that case, /predict returns a clear 503 until the model is registered and the service is restarted (or reloaded).</li></ul><p>This is an important production habit: do not take down the whole service just because a dependency is temporarily missing.</p><p><strong>3) Health and model visibility endpoints</strong></p><p>The service exposes:</p><ul><li>/health: confirms the process is running and whether a model is currently loaded.</li><li>/model: reads the Model Registry state and reports the latest version in the requested stage (and its run_id when available).</li></ul><p>These endpoints make it easy to debug issues like “model not loaded,” “wrong model name,” or “registry empty” without reading container logs first.</p><p><strong>4) Prediction path with feature parity</strong></p><p>/predict accepts raw I and Q arrays (paired samples). The service:</p><ul><li>validates I and Q are the same length,</li><li>converts them to numeric arrays,</li><li>computes engineered features using the same shared feature function used in training,</li><li>orders features consistently to match the training schema,</li><li>runs inference using the loaded MLflow model,</li><li>and returns the predicted modulation class.</li></ul><p>This enforces a critical MLOps principle: training and inference use the same feature logic (no silent divergence).</p><p><strong>5) Built-in observability with Prometheus metrics</strong></p><p>The service publishes:</p><ul><li>a request counter (per endpoint),</li><li>and a latency histogram (per endpoint),</li><li>and exposes them at: /metrics</li></ul><p>Prometheus scrapes /metrics, Grafana visualizes trends, and you get immediate visibility into usage and performance (instead of guessing when the API slows down or errors spike).</p><h4>What you get at the end of this step</h4><p>A production internal inference API that is:</p><ul><li>self-serve (simple HTTP interface),</li><li>registry-driven (loads the current Production model),</li><li>robust (starts even when the model is not available yet),</li><li>observable (metrics for requests and latency),</li><li>and consistent with training (shared feature extraction).</li></ul><pre>cat &gt; api/app.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br># Standard library imports<br>import logging<br>import os<br>import time<br>from typing import Optional<br><br># Third-party imports for numeric processing and ML<br>import numpy as np<br>import pandas as pd<br>import mlflow<br>from mlflow.tracking import MlflowClient<br>from mlflow.exceptions import RestException<br><br># Web framework imports<br>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel, Field<br><br># Prometheus metrics (exposed via /metrics)<br>from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST<br>from starlette.responses import Response<br><br># Project-local feature engineering from raw I/Q samples<br>from signalforge.feature_extract import features_from_iq<br><br># -----------------------------<br># Logging<br># -----------------------------<br>logging.basicConfig(level=logging.INFO)<br>log = logging.getLogger(&quot;signalforge.api&quot;)<br><br># -----------------------------<br># Configuration (from env vars)<br># -----------------------------<br># MLflow tracking server address.<br># In Docker Compose this typically resolves via service name (mlflow).<br>MLFLOW_TRACKING_URI = os.getenv(&quot;MLFLOW_TRACKING_URI&quot;, &quot;http://mlflow:5000&quot;)<br><br># Registered model name in MLflow Model Registry.<br>MODEL_NAME = os.getenv(&quot;MODEL_NAME&quot;, &quot;rf_modulation_classifier&quot;)<br><br># Model stage to load (Production/Staging/etc.) from Model Registry.<br>MODEL_STAGE = os.getenv(&quot;MODEL_STAGE&quot;, &quot;Production&quot;)<br><br># Initialize MLflow client + tracking config once at import time.<br>mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)<br>client = MlflowClient()<br><br># -----------------------------<br># Prometheus metrics<br># -----------------------------<br># Total request counter by endpoint.<br>REQS = Counter(&quot;signalforge_requests_total&quot;, &quot;Total requests&quot;, [&quot;endpoint&quot;])<br><br># Request latency histogram by endpoint (seconds).<br>LAT = Histogram(&quot;signalforge_request_latency_seconds&quot;, &quot;Latency&quot;, [&quot;endpoint&quot;])<br><br># -----------------------------<br># FastAPI app setup<br># -----------------------------<br>app = FastAPI(title=&quot;HybridSignalForge API&quot;)<br><br># -----------------------------<br># Request schema<br># -----------------------------<br>class PredictRequest(BaseModel):<br>    # I/Q are lists of float samples. We enforce a minimum length to avoid empty / tiny inputs.<br>    i: list[float] = Field(..., min_length=16)<br>    q: list[float] = Field(..., min_length=16)<br><br># -----------------------------<br># Model loading helpers<br># -----------------------------<br>def load_model():<br>    &quot;&quot;&quot;<br>    Load the MLflow model from the Model Registry using:<br>      models:/&lt;MODEL_NAME&gt;/&lt;MODEL_STAGE&gt;<br><br>    Raises if:<br>    - MLflow is not reachable<br>    - The model name does not exist in registry<br>    - No version exists for the requested stage<br>    - Artifacts are not accessible (S3/MinIO permissions, etc.)<br>    &quot;&quot;&quot;<br>    uri = f&quot;models:/{MODEL_NAME}/{MODEL_STAGE}&quot;<br>    return mlflow.pyfunc.load_model(uri)<br><br>def is_model_missing_error(e: Exception) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Detect the common case where the model isn&#39;t registered yet.<br>    MLflow raises RestException with RESOURCE_DOES_NOT_EXIST for missing registered models.<br>    &quot;&quot;&quot;<br>    if isinstance(e, RestException):<br>        msg = str(e)<br>        return &quot;RESOURCE_DOES_NOT_EXIST&quot; in msg and f&quot;name={MODEL_NAME}&quot; in msg<br>    return False<br><br># Global model handle (populated at app startup). None means &quot;not loaded yet&quot;.<br>MODEL: Optional[mlflow.pyfunc.PyFuncModel] = None<br><br>def ensure_model_loaded() -&gt; bool:<br>    &quot;&quot;&quot;<br>    Best-effort lazy load. Returns True if model is loaded, False otherwise.<br>    &quot;&quot;&quot;<br>    global MODEL<br>    if MODEL is not None:<br>        return True<br>    try:<br>        MODEL = load_model()<br>        log.info(&quot;Model loaded on-demand: name=%s stage=%s&quot;, MODEL_NAME, MODEL_STAGE)<br>        return True<br>    except Exception as e:<br>        MODEL = None<br>        if is_model_missing_error(e):<br>            log.warning(<br>                &quot;MLflow model not found yet: name=%s stage=%s. &quot;<br>                &quot;Register the model and retry.&quot;,<br>                MODEL_NAME,<br>                MODEL_STAGE,<br>            )<br>        else:<br>            log.exception(&quot;Model load failed on-demand: %s&quot;, e)<br>        return False<br><br>@app.on_event(&quot;startup&quot;)<br>def startup():<br>    &quot;&quot;&quot;<br>    FastAPI startup hook.<br><br>    Key behavior:<br>    - Do NOT crash the whole API if the model isn&#39;t registered yet.<br>    - Start the API and expose /health and /model for debugging.<br>    - /predict will return 503 until a model is available (and API is restarted or reloaded).<br>    &quot;&quot;&quot;<br>    global MODEL<br>    try:<br>        MODEL = load_model()<br>        log.info(&quot;Model loaded: name=%s stage=%s&quot;, MODEL_NAME, MODEL_STAGE)<br>    except Exception as e:<br>        MODEL = None<br>        if is_model_missing_error(e):<br>            log.warning(<br>                &quot;MLflow model not found in registry yet: name=%s stage=%s. &quot;<br>                &quot;API will start without model. Register the model and restart the API.&quot;,<br>                MODEL_NAME,<br>                MODEL_STAGE,<br>            )<br>        else:<br>            log.exception(<br>                &quot;Model load failed (non-registry-missing error). API will start without model. Error: %s&quot;,<br>                e,<br>            )<br><br># -----------------------------<br># Health endpoint<br># -----------------------------<br>@app.get(&quot;/health&quot;)<br>def health():<br>    &quot;&quot;&quot;<br>    Health check endpoint.<br><br>    - ok=True means the API process is up.<br>    - model_loaded indicates whether the ML model is ready for /predict.<br>    &quot;&quot;&quot;<br>    return {<br>        &quot;ok&quot;: True,<br>        &quot;model_loaded&quot;: MODEL is not None,<br>        &quot;model&quot;: MODEL_NAME,<br>        &quot;stage&quot;: MODEL_STAGE,<br>        &quot;mlflow_tracking_uri&quot;: MLFLOW_TRACKING_URI,<br>    }<br><br># -----------------------------<br># Model metadata endpoint<br># -----------------------------<br>@app.get(&quot;/model&quot;)<br>def model_info():<br>    &quot;&quot;&quot;<br>    Returns model registry information:<br>    - model name<br>    - stage requested<br>    - latest version in that stage (if any) and its run_id<br><br>    If the model does not exist yet in the registry, returns version=None.<br>    &quot;&quot;&quot;<br>    try:<br>        prod = client.get_latest_versions(MODEL_NAME, stages=[MODEL_STAGE])<br>    except RestException as e:<br>        # Model name doesn&#39;t exist in registry yet<br>        if &quot;RESOURCE_DOES_NOT_EXIST&quot; in str(e):<br>            return {&quot;model&quot;: MODEL_NAME, &quot;stage&quot;: MODEL_STAGE, &quot;version&quot;: None}<br>        raise<br><br>    if not prod:<br>        return {&quot;model&quot;: MODEL_NAME, &quot;stage&quot;: MODEL_STAGE, &quot;version&quot;: None}<br><br>    v = prod[0]<br>    return {&quot;model&quot;: MODEL_NAME, &quot;stage&quot;: MODEL_STAGE, &quot;version&quot;: v.version, &quot;run_id&quot;: v.run_id}<br><br># -----------------------------<br># Prediction endpoint<br># -----------------------------<br>@app.post(&quot;/predict&quot;)<br>def predict(req: PredictRequest):<br>    &quot;&quot;&quot;<br>    Converts incoming raw I/Q samples into engineered features, then calls the loaded ML model.<br>    Also records Prometheus request count + latency for the endpoint.<br><br>    If the model is not loaded yet, returns 503.<br>    &quot;&quot;&quot;<br>    # If model isn&#39;t available, fail fast with a clear error.<br>    if not ensure_model_loaded():<br>        raise HTTPException(<br>            status_code=503,<br>            detail=(<br>                f&quot;Model not loaded yet. Expected MLflow registry model &#39;{MODEL_NAME}&#39; &quot;<br>                f&quot;at stage &#39;{MODEL_STAGE}&#39;. Register the model in MLflow and restart the API.&quot;<br>            ),<br>        )<br><br>    # Start timer + increment request counter.<br>    t0 = time.time()<br>    REQS.labels(endpoint=&quot;/predict&quot;).inc()<br><br>    # Input validation: I and Q must be same length for paired samples.<br>    if len(req.i) != len(req.q):<br>        raise HTTPException(status_code=400, detail=&quot;i and q must have same length&quot;)<br><br>    # Convert lists to numpy arrays for feature extraction.<br>    i = np.array(req.i, dtype=np.float32)<br>    q = np.array(req.q, dtype=np.float32)<br><br>    # Compute features from raw I/Q.<br>    feat = features_from_iq(i, q)<br><br>    # Feature order must match what the model was trained on.<br>    feature_keys = [<br>        &quot;rms&quot;, &quot;p2p_i&quot;, &quot;p2p_q&quot;, &quot;mean_i&quot;, &quot;std_i&quot;, &quot;mean_q&quot;, &quot;std_q&quot;,<br>        &quot;skew_i&quot;, &quot;kurt_i&quot;, &quot;skew_q&quot;, &quot;kurt_q&quot;, &quot;iq_imbalance&quot;, &quot;fft_peak&quot;<br>    ]<br><br>    # Build a single-row 2D array from the feature dict in the expected order.<br>    X = np.array([[feat[k] for k in feature_keys]], dtype=float)<br><br>    # Model expects a DataFrame with matching column names.<br>    pred = MODEL.predict(pd.DataFrame(X, columns=feature_keys))<br><br>    # Record request latency.<br>    LAT.labels(endpoint=&quot;/predict&quot;).observe(time.time() - t0)<br><br>    # Return prediction (stringified for JSON safety) and raw feature dictionary for debugging.<br>    return {&quot;prediction&quot;: str(pred[0]), &quot;features&quot;: feat}<br><br># -----------------------------<br># Prometheus scrape endpoint<br># -----------------------------<br>@app.get(&quot;/metrics&quot;)<br>def metrics():<br>    &quot;&quot;&quot;<br>    Exposes Prometheus metrics in the standard text format.<br>    Configure Prometheus to scrape this endpoint.<br>    &quot;&quot;&quot;<br>    data = generate_latest()<br>    return Response(content=data, media_type=CONTENT_TYPE_LATEST)<br>EOF</pre><h3>Step 16: Orchestrate the full workflow with Airflow</h3><p>This is where everything becomes a real platform workflow. We define an Airflow DAG that connects all components into a single, repeatable, end-to-end pipeline: create a versioned branch in lakeFS, generate and ingest raw data, enforce a quality gate, run Spark feature engineering, commit the derived dataset, train and register a model in MLflow, run a drift check with an optional rollback decision, and finally merge the data branch back into main.</p><p>The platform idea here is “pipeline as code”:</p><ul><li>Every step is automated,</li><li>Every dependency is explicit,</li><li>Lineage is captured through lakeFS commits and branch merges,</li><li>And the whole workflow can be rerun consistently for new runs or new data distributions.</li></ul><h4>What the DAG is doing (high level)</h4><p><strong>1) Build a lakeFS context from environment variables</strong></p><p>The DAG constructs a shared lakeFS context (repo, endpoint, credentials) from env vars so all tasks use consistent configuration. This avoids hardcoding and makes the DAG portable across environments.</p><p><strong>2) Bootstrap lakeFS (idempotent)</strong></p><p>First, we ensure lakeFS is ready (setup + repo exists). This eliminates manual UI setup and guarantees the pipeline can run on a fresh environment.</p><p><strong>3) Create an isolated lakeFS branch for the run</strong></p><p>For each DAG run, we generate:</p><ul><li>a run_id (timestamp + short UUID)</li><li>and a corresponding branch name derived from that run_id</li></ul><p>We create the branch from main. This gives us isolation: all raw and derived artifacts for this run live under a branch namespace, so experiments do not step on each other.</p><p>We store run_id and branch in XCom so downstream tasks can reference the exact run context.</p><p><strong>4) Ingest raw data into the versioned lake</strong></p><p>The pipeline generates synthetic raw I/Q data and uploads:</p><ul><li>a Parquet dataset (structured data)</li><li>and a JSON manifest (semi-structured metadata)</li></ul><p>into the lakeFS S3 gateway under a branch-specific path. This makes the ingestion reproducible and tied to the run_id.</p><p><strong>5) Run the quality gate and persist the report</strong></p><p>Before any feature engineering or training, we download the raw dataset, validate it, generate a quality report, and upload that report back into lakeFS as an artifact. If the quality gate fails (for example, window length mismatch), the DAG stops immediately. This is your “trust enforcement” checkpoint.</p><p><strong>6) Launch Spark feature engineering</strong></p><p>The DAG triggers the Spark feature engineering job from Airflow. Operationally, it does this by executing a spark-submit command inside the Spark master container (via the Docker API), passing:</p><ul><li>repo, branch, run_id</li><li>lakeFS endpoint and credentials</li></ul><p>The Spark job reads raw data from the versioned lake and writes feature Parquet back into the same branch.</p><blockquote>Key idea: distributed compute for transformations, versioned storage for reproducibility.</blockquote><p><strong>7) Commit the feature dataset to lakeFS</strong></p><p>After Spark writes the features, we create a lakeFS commit on that branch. This is a crucial lineage step:</p><ul><li>It marks a stable “features version” for this run</li><li>and it becomes the reference point for training, comparisons, and audit trails</li></ul><p><strong>8) Train, log to MLflow, and promote a model</strong></p><p>Next the DAG runs training:</p><ul><li>loads the engineered features for (branch, run_id),</li><li>trains a model,</li><li>logs params, metrics, and lineage tags into MLflow,</li><li>registers the model under a stable registry name,</li><li>and promotes the latest version to Production (archiving any existing Production model first).</li></ul><p>We also capture values like model_name, baseline_run_id, MLflow run id, and model version in XCom for downstream logic.</p><p><strong>9) Drift check and merge decision</strong></p><p>Finally, we compare this run’s features against a baseline run:</p><ul><li>compute drift_share,</li><li>push drift metrics to monitoring (Pushgateway → Prometheus → Grafana),</li><li>optionally roll back the Production model if drift exceeds threshold,</li><li>and decide whether to merge the lakeFS branch into main.</li></ul><p>In this DAG, drift is used as a merge gate:</p><ul><li>If drift_share is too high, the merge is blocked (the run is flagged as risky),</li><li>Otherwise, we merge the run branch into main, making the run’s curated outputs part of the canonical dataset history.</li></ul><pre>mkdir -p airflow/dags<br><br>cat &gt; airflow/dags/signalforge_pipeline.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import os<br>import uuid<br>from datetime import datetime, timedelta<br><br>from airflow import DAG<br>from airflow.providers.standard.operators.python import PythonOperator<br><br><br>def _ctx_from_env():<br>    from signalforge.lakefs_ops import LakeFSContext<br><br>    return LakeFSContext(<br>        repo=os.environ[&quot;LAKEFS_REPO&quot;],<br>        endpoint=os.environ[&quot;LAKEFS_ENDPOINT_INTERNAL&quot;],<br>        access_key_id=os.environ[&quot;LAKEFS_BOOTSTRAP_ACCESS_KEY_ID&quot;],<br>        secret_access_key=os.environ[&quot;LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY&quot;],<br>    )<br><br><br>def _xcom_required(ti, task_id: str, key: str):<br>    v = ti.xcom_pull(task_ids=task_id, key=key)<br>    if v is None:<br>        raise RuntimeError(<br>            f&quot;Missing XCom &#39;{key}&#39; from task &#39;{task_id}&#39;. &quot;<br>            &quot;If you are running a single task with `airflow tasks test`, &quot;<br>            &quot;run upstream tasks first or use `airflow dags test`.&quot;<br>        )<br>    return v<br><br><br>def bootstrap_lakefs():<br>    from signalforge import lakefs_bootstrap<br><br>    lakefs_bootstrap.ensure_setup_and_repo()<br><br><br>def create_branch(ti, logical_date=None, **_):<br>    from signalforge.lakefs_ops import create_branch<br><br>    ctx = _ctx_from_env()<br><br>    # stable-ish run id for a dagrun<br>    stamp = (logical_date or datetime.utcnow()).strftime(&quot;%Y%m%d-%H%M%S&quot;)<br>    run_id = f&quot;{stamp}-{uuid.uuid4().hex[:8]}&quot;<br>    branch = f&quot;run_{run_id.replace(&#39;-&#39;, &#39;_&#39;)}&quot;<br><br>    # ensure branch exists from main<br>    create_branch(ctx, source_ref=&quot;main&quot;, new_branch=branch)<br><br>    ti.xcom_push(key=&quot;run_id&quot;, value=run_id)<br>    ti.xcom_push(key=&quot;branch&quot;, value=branch)<br><br><br>def ingest_raw(ti, **_):<br>    import tempfile<br><br>    from signalforge.data_gen import default_spec, generate_raw_batch<br>    from signalforge.lakefs_ops import lakefs_s3_client, ensure_repo_visible_via_s3<br><br>    ctx = _ctx_from_env()<br>    ensure_repo_visible_via_s3(ctx)<br><br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br><br>    s3 = lakefs_s3_client(ctx)<br>    bucket = ctx.repo<br>    raw_key = f&quot;{branch}/raw/{run_id}/raw.parquet&quot;<br>    manifest_key = f&quot;{branch}/raw/{run_id}/manifest.json&quot;<br><br>    with tempfile.TemporaryDirectory() as td:<br>        parquet_path, manifest_path = generate_raw_batch(td, run_id, default_spec())<br>        s3.upload_file(parquet_path, bucket, raw_key)<br>        s3.upload_file(manifest_path, bucket, manifest_key)<br><br><br>def quality_gate(ti, **_):<br>    import os<br>    import tempfile<br><br>    from signalforge.quality import run_quality_checks<br>    from signalforge.lakefs_ops import lakefs_s3_client, ensure_repo_visible_via_s3<br><br>    ctx = _ctx_from_env()<br>    ensure_repo_visible_via_s3(ctx)<br><br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br><br>    s3 = lakefs_s3_client(ctx)<br>    bucket = ctx.repo<br>    raw_key = f&quot;{branch}/raw/{run_id}/raw.parquet&quot;<br>    report_key = f&quot;{branch}/quality/{run_id}/quality_report.json&quot;<br><br>    with tempfile.TemporaryDirectory() as td:<br>        raw_path = os.path.join(td, &quot;raw.parquet&quot;)<br>        report_path = os.path.join(td, &quot;quality_report.json&quot;)<br>        s3.download_file(bucket, raw_key, raw_path)<br><br>        result = run_quality_checks(raw_path, report_path)<br>        s3.upload_file(report_path, bucket, report_key)<br><br>    if not result.ok:<br>        raise RuntimeError(f&quot;Quality gate failed: {result}&quot;)<br><br><br>def spark_feature_engineering(ti, **_):<br>    &quot;&quot;&quot;<br>    Launch Spark job via docker SDK to compute features and write to lakeFS S3 gateway.<br>    &quot;&quot;&quot;<br>    import docker<br><br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br><br>    client = docker.from_env()<br>    name_override = os.getenv(&quot;SPARK_MASTER_CONTAINER&quot;)<br>    if name_override:<br>        try:<br>            spark_master = client.containers.get(name_override)<br>        except docker.errors.NotFound as e:<br>            raise RuntimeError(<br>                f&quot;SPARK_MASTER_CONTAINER &#39;{name_override}&#39; not found.&quot;<br>            ) from e<br>    else:<br>        containers = client.containers.list()<br>        matches = []<br>        for c in containers:<br>            labels = c.labels or {}<br>            if labels.get(&quot;com.docker.compose.service&quot;) == &quot;spark-master&quot;:<br>                matches.append(c)<br>                continue<br>            if &quot;spark-master&quot; in (c.name or &quot;&quot;):<br>                matches.append(c)<br><br>        if not matches:<br>            names = &quot;, &quot;.join(sorted(c.name for c in containers)) or &quot;(none)&quot;<br>            raise RuntimeError(<br>                &quot;spark-master container not found. Is docker-compose.spark.yml running? &quot;<br>                f&quot;Running containers: {names}&quot;<br>            )<br><br>        spark_master = sorted(matches, key=lambda c: c.name)[0]<br><br>    cmd = [<br>        &quot;/opt/spark/bin/spark-submit&quot;,<br>        &quot;--master&quot;,<br>        &quot;spark://spark-master:7077&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.sql.shuffle.partitions=8&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.default.parallelism=8&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.executor.cores=1&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.executor.memory=2g&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.driver.memory=2g&quot;,<br>        &quot;--packages&quot;,<br>        &quot;org.apache.hadoop:hadoop-aws:3.3.4&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.driverEnv.PYTHONPATH=/opt/signalforge/src&quot;,<br>        &quot;--conf&quot;,<br>        &quot;spark.executorEnv.PYTHONPATH=/opt/signalforge/src&quot;,<br>        &quot;/opt/spark_jobs/feature_engineering.py&quot;,<br>        &quot;--repo&quot;,<br>        os.environ[&quot;LAKEFS_REPO&quot;],<br>        &quot;--branch&quot;,<br>        branch,<br>        &quot;--run-id&quot;,<br>        run_id,<br>        &quot;--lakefs-endpoint&quot;,<br>        os.environ[&quot;LAKEFS_ENDPOINT_INTERNAL&quot;],<br>        &quot;--access-key&quot;,<br>        os.environ[&quot;LAKEFS_BOOTSTRAP_ACCESS_KEY_ID&quot;],<br>        &quot;--secret-key&quot;,<br>        os.environ[&quot;LAKEFS_BOOTSTRAP_SECRET_ACCESS_KEY&quot;],<br>    ]<br><br>    result = spark_master.exec_run(cmd, stdout=True, stderr=True)<br>    if result.exit_code != 0:<br>        output = result.output.decode(&quot;utf-8&quot;, errors=&quot;replace&quot;) if result.output else &quot;&quot;<br>        raise RuntimeError(f&quot;Spark job failed (exit_code={result.exit_code}).\n{output}&quot;)<br><br><br>def commit_features(ti, **_):<br>    from signalforge.lakefs_ops import commit_changes<br><br>    ctx = _ctx_from_env()<br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br><br>    commit_id = commit_changes(ctx, branch=branch, message=f&quot;features for run {run_id}&quot;)<br>    ti.xcom_push(key=&quot;commit_id&quot;, value=commit_id)<br><br><br>def train_model(ti, **_):<br>    &quot;&quot;&quot;<br>    Train a model from feature store data and log into MLflow.<br>    &quot;&quot;&quot;<br>    from signalforge.train import train_and_register<br><br>    ctx = _ctx_from_env()<br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br><br>    model_name = os.getenv(&quot;SIGNALFORGE_MODEL_NAME&quot;, &quot;rf_modulation_classifier&quot;)<br>    baseline_run_id = os.getenv(&quot;SIGNALFORGE_BASELINE_RUN_ID&quot;, &quot;&quot;)<br><br>    out = train_and_register(ctx=ctx, branch=branch, run_id=run_id, model_name=model_name)<br>    if not baseline_run_id:<br>        baseline_run_id = run_id<br><br>    ti.xcom_push(key=&quot;model_name&quot;, value=model_name)<br>    ti.xcom_push(key=&quot;baseline_run_id&quot;, value=baseline_run_id)<br>    ti.xcom_push(key=&quot;mlflow_run_id&quot;, value=out.get(&quot;mlflow_run_id&quot;))<br>    ti.xcom_push(key=&quot;model_version&quot;, value=out.get(&quot;model_version&quot;))<br><br><br>def drift_and_merge(ti, **_):<br>    from signalforge.drift import drift_check<br>    from signalforge.lakefs_ops import merge_branch<br><br>    ctx = _ctx_from_env()<br>    run_id = _xcom_required(ti, &quot;create_branch&quot;, &quot;run_id&quot;)<br>    branch = _xcom_required(ti, &quot;create_branch&quot;, &quot;branch&quot;)<br>    model_name = _xcom_required(ti, &quot;train_model&quot;, &quot;model_name&quot;)<br>    baseline_run_id = _xcom_required(ti, &quot;train_model&quot;, &quot;baseline_run_id&quot;)<br><br>    res = drift_check(<br>        ctx=ctx,<br>        branch=branch,<br>        baseline_run_id=baseline_run_id,<br>        current_run_id=run_id,<br>        model_name=model_name,<br>    )<br><br>    # If drift check decides rollback, you may still merge code/data or choose to block.<br>    # For now: merge branch into main if drift is not too high.<br>    drift_share = float(res.get(&quot;drift_share&quot;, 0.0))<br>    if drift_share &gt; float(os.getenv(&quot;SIGNALFORGE_DRIFT_THRESHOLD&quot;, &quot;0.3&quot;)):<br>        raise RuntimeError(f&quot;Drift too high (share={drift_share}). Merge blocked. res={res}&quot;)<br><br>    merge_branch(ctx, source_branch=branch, destination_branch=&quot;main&quot;)<br><br><br>default_args = {<br>    &quot;owner&quot;: &quot;airflow&quot;,<br>    &quot;retries&quot;: 0,<br>    &quot;retry_delay&quot;: timedelta(minutes=1),<br>}<br><br>with DAG(<br>    dag_id=&quot;signalforge_end_to_end&quot;,<br>    default_args=default_args,<br>    start_date=datetime(2026, 1, 1),<br>    schedule=None,<br>    catchup=False,<br>    tags=[&quot;signalforge&quot;],<br>) as dag:<br><br>    t0 = PythonOperator(task_id=&quot;bootstrap_lakefs&quot;, python_callable=bootstrap_lakefs)<br>    t1 = PythonOperator(task_id=&quot;create_branch&quot;, python_callable=create_branch)<br>    t2 = PythonOperator(task_id=&quot;ingest_raw&quot;, python_callable=ingest_raw)<br>    t3 = PythonOperator(task_id=&quot;quality_gate&quot;, python_callable=quality_gate)<br>    t4 = PythonOperator(task_id=&quot;spark_feature_engineering&quot;, python_callable=spark_feature_engineering)<br>    t5 = PythonOperator(task_id=&quot;commit_features&quot;, python_callable=commit_features)<br>    t6 = PythonOperator(task_id=&quot;train_model&quot;, python_callable=train_model)<br>    t7 = PythonOperator(task_id=&quot;drift_and_merge&quot;, python_callable=drift_and_merge)<br><br>    t0 &gt;&gt; t1 &gt;&gt; t2 &gt;&gt; t3 &gt;&gt; t4 &gt;&gt; t5 &gt;&gt; t6 &gt;&gt; t7<br>EOF</pre><h4>How to verify end-to-end behavior (what you should observe)</h4><p><strong>1) Bring up the platform containers and confirm health</strong></p><ul><li>Start the stack with Docker Compose and ensure services are healthy (especially Postgres, lakeFS, Airflow, Spark, MLflow).</li></ul><pre>docker compose up -d # Or, docker compose up -d --build<br>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTBBvlmQlsXA61m6GDnHZA.png" /><figcaption>Fig: Output docker compose up -d</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMIbqU8wBOzZLEWn_ArNNg.png" /><figcaption>Fig: Output docker ps</figcaption></figure><p><strong>2) Trigger the DAG from the Airflow UI or CLI</strong></p><ul><li>Visit Airflow UI</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7VHDRKY-J0jjWQk0WWX97A.png" /><figcaption>Fig: Airflow UI, Dags Page</figcaption></figure><ul><li>Turn on the DAG in the UI and trigger a run (or trigger via the Airflow CLI inside the container).</li></ul><pre>docker compose exec airflow-webserver airflow dags trigger signalforge_end_to_end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyrvxTbPnX45pM7LihQX6g.png" /><figcaption>Fig: Trigger DAG run</figcaption></figure><p><strong>3) Expected outcomes across the platform UIs</strong></p><ul><li><strong>Airflow UI:</strong> the DAG run succeeds (all tasks green) or fails at a clear gate (quality, Spark, drift).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLCJgDRCt0IgxpeA494Hig.png" /><figcaption>Fig: DAG run succeeds</figcaption></figure><ul><li><strong>lakeFS UI:</strong> a new run branch is created, commits appear (for features), and successful runs are merged into main.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBW8yaONlzDIqZVNnp9Y1Q.png" /><figcaption>Fig: LakeFS, Confirm the run branch was created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwui8X-V4YCY8lZYc4JphA.png" /><figcaption>Fig: lakeFS, Confirm commits exist (features commit is the key one)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FytQS2I8wiWeoTqNkGljew.png" /><figcaption>Fig: lakeFS, Confirm merge into main happened by compare main content changed</figcaption></figure><ul><li><strong>MLflow UI:</strong> an experiment run is created, and a new model version is registered and promoted to Production.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y74vxq-TzyS8UIHBTGG25w.png" /><figcaption>Fig: MLflow, Confirm experiment and run</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11EOwN88kwOmy85G0oYP0w.png" /><figcaption>Fig: MLflow, Confirm model registry and Production stage (After more DAG runs)</figcaption></figure><ul><li><strong>Prometheus/Grafana:</strong> drift metrics are present (via Pushgateway) and can be visualized over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wk-xzsTgOn31O6f4msTkVg.png" /><figcaption>Fig: Prometheus, query box run</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcLPviQ14Mw6zPiz-LQuUA.png" /><figcaption>Fig: Grafana Dashboard</figcaption></figure><ul><li><strong>FastAPI:</strong> remains ready to serve predictions, and can load the latest Production model once the registry is populated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTaqMxfq_CIJoSX5ZPoWDw.png" /><figcaption>Fig: FastAPI</figcaption></figure><p>The net result is a complete “mini internal AI platform” workflow: versioned data + orchestration + distributed transforms + tracked training + governed model promotion + drift monitoring + safe merge/rollback decisions.</p><h3>Step 17: Makefile (one-command flows)</h3><p>As a platform engineering best practice, we make the system easy to run, test, and operate. Multi-container platforms can feel intimidating because there are many commands, the order matters, and small mistakes waste time. A Makefile solves that by giving the project a few standard, memorable “one-command flows” that anyone on the team can use.</p><h4>What the Makefile provides (high-level)</h4><p>We define short targets that wrap the most common operational actions:</p><p><strong>1) Bring the platform up</strong></p><p>A single command starts the entire stack and builds images when needed. This standardizes the “happy path” and avoids different people running different docker compose commands.</p><p><strong>2) Bring the platform down cleanly</strong></p><p>We stop the stack and remove volumes when we want a clean reset. This is useful during development when databases, object storage, or metadata state gets messy.</p><p><strong>3) Bootstrap lakeFS</strong></p><p>We run the lakeFS bootstrap module inside the Airflow container. This ensures the initialization is executed from within the same network and environment where orchestration runs, which is closer to real platform behavior and reduces “works on host, fails in container” issues.</p><p><strong>4) Trigger the end-to-end pipeline</strong></p><p>We provide a simple target to trigger the Airflow DAG from the CLI. This makes it easy to run an end-to-end test without clicking through the UI.</p><p><strong>5) Tail key logs for debugging</strong></p><p>A log target focuses on the services you most often debug during orchestration: Airflow scheduler and webserver. This gives fast feedback when tasks are stuck, dependencies are missing, or connections are misconfigured.</p><h4>How you run the standard flow</h4><p>A typical “from zero to pipeline run” sequence looks like this:</p><ul><li>Start the platform stack.</li><li>Run the Airflow init step once (to set up Airflow metadata and admin user, if your setup requires it).</li><li>Bootstrap lakeFS so the repository and credentials are ready.</li><li>Trigger the DAG to run the full workflow.</li></ul><p>The point is not the Makefile itself. The point is operational ergonomics: reliable, repeatable commands that make the platform easy for someone else to run in minutes.</p><pre>cat &gt; Makefile &lt;&lt; &#39;EOF&#39;<br>up:<br> docker compose up -d --build<br><br>down:<br> docker compose down -v<br><br>bootstrap:<br> docker compose exec airflow-webserver python -m signalforge.lakefs_bootstrap<br><br>trigger:<br> docker compose exec airflow-webserver airflow dags trigger signalforge_end_to_end<br><br>logs-airflow:<br> docker compose logs -f airflow-scheduler airflow-webserver<br>EOF</pre><p>Run:</p><pre>make up<br>docker compose run --rm airflow-init<br><br>make bootstrap<br><br>make trigger</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHtFZANWxACM55thw9hndw.png" /><figcaption>Fig: Make Output</figcaption></figure><h3>Step 18: Simple SDK (developer enablement)</h3><p>In this step, we add a tiny Python SDK that wraps our FastAPI endpoints into a clean, easy-to-use client. This is a classic platform engineering move: many internal users should be able to consume the platform without learning the full stack (MLflow, lakeFS, Docker networking, and pipeline wiring). A small SDK makes adoption smoother, standardizes how people call the service, and reduces copy-paste errors across teams.</p><h4>Why an SDK helps</h4><p>Even if the platform exposes a REST API, different teams often:</p><ul><li>hardcode URLs differently,</li><li>forget timeouts,</li><li>or implement slightly different request formats.</li></ul><h4>A shared client library provides</h4><ul><li>a stable interface (method calls instead of raw HTTP),</li><li>consistent defaults (base URL and timeouts),</li><li>and a single place to improve error handling later (retries, better exceptions, auth headers, tracing).</li></ul><h4>What the client does (high level)</h4><p>The SignalForgeClient is intentionally small and focused on the most common “consumer” needs:</p><p><strong>1) health()</strong></p><p>Calls /health to confirm:</p><ul><li>the service is running,</li><li>and whether the model is loaded and ready for predictions.</li></ul><p><strong>2) model()</strong></p><p>Calls /model to fetch the current registry state:</p><ul><li>which model name and stage are being served,</li><li>and which version/run_id is active (when available).</li></ul><p><strong>3) predict(i, q)</strong></p><p>Calls /predict with raw I/Q arrays and returns:</p><ul><li>the predicted modulation class,</li><li>plus any debug payload the API returns (like computed features).</li></ul><pre>mkdir -p sdk<br><br>cat &gt; sdk/signalforge_client.py &lt;&lt; &#39;EOF&#39;<br>from __future__ import annotations<br><br>import requests<br><br>class SignalForgeClient:<br>    def __init__(self, base_url: str = &quot;http://localhost:9000&quot;):<br>        self.base_url = base_url.rstrip(&quot;/&quot;)<br><br>    def health(self) -&gt; dict:<br>        return requests.get(f&quot;{self.base_url}/health&quot;, timeout=10).json()<br><br>    def model(self) -&gt; dict:<br>        return requests.get(f&quot;{self.base_url}/model&quot;, timeout=10).json()<br><br>    def predict(self, i: list[float], q: list[float]) -&gt; dict:<br>        payload = {&quot;i&quot;: i, &quot;q&quot;: q}<br>        return requests.post(f&quot;{self.base_url}/predict&quot;, json=payload, timeout=30).json()<br>EOF</pre><h4>Quick test flow</h4><p>A minimal smoke test is:</p><ul><li>instantiate the client pointing to the local API,</li><li>call health() to confirm readiness,</li><li>call model() to confirm the registry state.</li></ul><p>Once a Production model is available and loaded by the API, you can call predict() with a valid I/Q window and get an inference response immediately.</p><pre>python -c &quot;from sdk.signalforge_client import SignalForgeClient; c=SignalForgeClient(); print(c.health()); print(c.model())&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3ipimJ9q1nqs13tqqUP_Q.png" /><figcaption>Fig: SDK Output</figcaption></figure><h3>Conclusion</h3><p>In this project, we built a complete AI platform. Even though it runs locally, it demonstrates the same responsibilities you would expect in production:</p><ul><li>End-to-end automation: ingestion → validation gates → Spark feature engineering → training → MLflow registry → drift monitoring</li><li>Reproducibility and governance: lakeFS branches and commits provide audit-friendly lineage and make dataset rollback practical</li><li>MLOps lifecycle control: MLflow tracking plus a model registry workflow, including automated promotion and a rollback hook</li><li>Hybrid-ready foundations: an on-prem-style local stack today, with a clear path to later adopt cloud object storage using Terraform when needed</li><li>Developer enablement: a FastAPI inference service with Prometheus metrics, plus a tiny SDK that makes consumption simple for other teams</li></ul><h4>Tradeoffs in this version</h4><p>To keep the project compact and runnable on a single machine, we made a few deliberate compromises:</p><ul><li>Spark submission approach: the orchestration submits Spark jobs from inside the local Docker environment (via access to the Docker socket). This is a good demonstration of orchestration and integration, but production deployments usually run Spark on Kubernetes or a managed Spark service and use dedicated operators or submission APIs.</li><li>Simplified drift baseline: drift is computed against a baseline run ID in a straightforward way for demonstration. In production, baselines are typically stored in a metadata store, and drift is evaluated using “current production window” versus “training (or last-validated) window” with more robust policies.</li><li>Lightweight governance: we do not add a full data catalog or lineage UI. Instead, lakeFS commit history plus stored quality and drift reports serve as a minimal but useful governance layer.</li></ul><h4>Where this platform can grow next</h4><p>This project is intentionally designed to be extendable. Natural next upgrades include:</p><ul><li>Add cloud-ready infrastructure: provision cloud object storage and identity policies using Terraform so the same lakeFS and MLflow patterns can operate in a cloud environment later.</li><li>Add end-to-end lineage: emit OpenLineage events from Airflow and store lineage records for richer observability and audit trails.</li><li>Replace local Spark with a production compute backend: Spark on Kubernetes (Spark Operator) or a managed Spark service for better scalability and operational separation.</li><li>Strengthen model operations: add explainability reports, continuous evaluation, and safer rollout patterns such as canary deployments.</li><li>Security hardening: add RBAC, stronger secret management (Vault or a managed secrets system), and tighter network controls.</li></ul><p>Overall, this was a solid end-to-end learning build in data platform engineering: not just training a model, but building the surrounding system that makes data and models reliable, observable, and safe to operate. Happy coding 🚀🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbFTHnpjLFjNpwz5gFqXaA.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1042a6a31398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SRE Production Stack on AWS]]></title>
            <link>https://medium.com/beyond-localhost/sre-mini-production-stack-on-aws-f1f9d92a9326?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f9d92a9326</guid>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 13:13:52 GMT</pubDate>
            <atom:updated>2026-04-18T11:10:36.931Z</atom:updated>
            <content:encoded><![CDATA[<h4>Complete, mini-production environment that demonstrates the SRE lifecycle, including IaC, monitoring, alerting, logging, runbooks, and incident simulations.</h4><p>If you were the on-call SRE for a web service, your job wouldn’t stop at “the app runs.” You’d build a production-ready environment where reliability can be measured, alerted on, investigated, and continuously improved.</p><p>This project guides you through building that on a single AWS EC2 VM:</p><ul><li>A VM provisioned with Terraform and secure networking</li><li>A Flask web service with /healthz, /metrics, and endpoints to simulate failures and latency</li><li>Prometheus for metrics collection</li><li>Grafana dashboards (Golden Signals + Host metrics)</li><li>Alertmanager with routing by severity (warning vs. critical)</li><li>Runbooks, SEV definitions, and postmortem templates</li><li>Two incident simulations (5xx spike and latency spike), with evidence across dashboards, logs, and alerts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwquChoPcmWX7k9IzPSW6w.png" /></figure><h3>Step 0: Local Machine Setup</h3><p>Before using AWS, prepare your local system for provisioning infrastructure, SSH access, and file transfers.</p><h4>0.1 Install Required Tools</h4><p>Update your system:</p><pre>sudo apt update<br>sudo apt -y upgrade</pre><p>Install Terraform:</p><pre># Ubuntu’s default apt repo can be outdated. Use HashiCorp’s official repo.<br><br>sudo apt-get update<br>sudo apt-get install -y gnupg software-properties-common<br><br>wget -O- https://apt.releases.hashicorp.com/gpg | \<br>  gpg --dearmor | \<br>  sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg &gt;/dev/null<br><br>echo &quot;deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \<br>https://apt.releases.hashicorp.com $(lsb_release -cs) main&quot; | \<br>sudo tee /etc/apt/sources.list.d/hashicorp.list<br><br>sudo apt-get update<br>sudo apt-get install -y terraform<br><br># Verify<br>terraform -version</pre><p>Install AWS CLI v2:</p><pre>cd /tmp<br>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;<br>unzip awscliv2.zip<br>sudo ./aws/install<br><br># Verify<br>aws --version</pre><p>Install other base tools:</p><pre>sudo apt install -y git openssh-client curl unzip ca-certificates gnupg lsb-release<br><br># Verify<br>git --version<br>ssh -V<br>curl --version</pre><h4>0.2 Configure AWS Credentials</h4><ol><li>Log in as the root AWS user and enable MFA.</li><li>Create an IAM user named sre-mini-admin, with console access and temporary AdministratorAccess.</li><li>Attach the AWS managed policy: SignInLocalDevelopmentAccess.</li><li>Use aws login to authenticate programmatically.</li></ol><blockquote>For learning purposes, many people temporarily attach AdministratorAccess to avoid permission debugging, then later replace it with least-privilege. (This is a practical approach, but do not use it permanently)</blockquote><pre># Clear any stale env credentials in this terminal<br>unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN<br>unset AWS_PROFILE AWS_DEFAULT_REGION AWS_REGION<br><br># Start login (use a dedicated profile)<br>aws login --profile sre-mini --region ap-south-1<br><br># A browser window opens (or you get a URL). <br># Sign in using the IAM user’s console credentials and complete the prompts.<br><br># Verify who you are<br>aws sts get-caller-identity --profile sre-mini<br><br># If this command works, it means your CLI session is valid, and AWS can issue temporary credentials for that profile.</pre><p>5. Export credentials to your shell:</p><blockquote>Run this in the same terminal where you will run Terraform.</blockquote><pre>eval &quot;$(aws configure export-credentials --profile sre-mini --format env)&quot;<br><br>export AWS_PROFILE=sre-mini<br>export AWS_REGION=ap-south-1<br>export AWS_EC2_METADATA_DISABLED=true # This stops Terraform/AWS SDK from wasting time trying EC2 metadata on your system.</pre><blockquote>In your environment, Terraform will pick them up automatically.</blockquote><p>6. (Optional) End session when done:</p><pre>aws logout --profile sre-mini</pre><h4>0.3 Create EC2 Key Pair (for Terraform)</h4><blockquote>Important clarification: You are not creating EC2 manually here.<br>You are only creating the Key Pair now. The EC2 instance will be created later by Terraform.</blockquote><p>You can do this by using the AWS Console, creating the key pair, downloading the .pem and moving it to ~./ssh and locking the permission. But here we will use the AWS console:</p><p>1. Pick a key pair name (must match Terraform key_name). <br>Example: sre-mini-key.</p><p>2. Create the key and save it directly to ~/.ssh:</p><pre>mkdir -p ~/.ssh<br><br>aws ec2 create-key-pair \<br>  --key-name sre-mini-key \<br>  --key-type rsa \<br>  --query &#39;KeyMaterial&#39; \<br>  --output text \<br>  --region ap-south-1 \<br>  --profile sre-mini &gt; ~/.ssh/sre-mini-key.pem</pre><p>3. Fix permissions:</p><pre>chmod 400 ~/.ssh/sre-mini-key.pem</pre><p>4. Confirm file exists and permissions are correct:</p><pre>ls -l ~/.ssh/sre-mini-key.pem</pre><h4>0.4 Capture Public IP</h4><pre>curl -s https://checkip.amazonaws.com</pre><p>Suppose it prints: 1.2.3.4 . Your CIDR becomes: 1.2.3.4/32.</p><p>You will pass this into Terraform as my_ip_cidr. You will use this to restrict SSH and observability UIs to only your IP.</p><h4>0.5 Final Local Checklist</h4><p>Verify all tools are installed and AWS credentials work:</p><pre># Tool versions<br>terraform -version<br>aws --version<br>git --version<br>ssh -V<br><br># Confirm AWS login is valid (use your profile)<br>aws sts get-caller-identity --profile sre-mini --region ap-south-1<br><br># Confirm public IP lookup works<br>curl -s https://checkip.amazonaws.com<br><br># Confirm the key file exists and permissions are strict<br>ls -l ~/.ssh/sre-mini-key.pem</pre><h3>Step 1: Recommended GitHub Repository Structure</h3><p>Organize your codebase like a production stack. Here’s the recommended structure:</p><pre>sre-mini-prod-aws/<br>├── README.md<br>├── terraform/<br>│   ├── main.tf<br>│   ├── variables.tf<br>│   ├── outputs.tf<br>│   └── user_data.sh<br>├── app/<br>│   ├── app.py<br>│   ├── requirements.txt<br>│   └── Dockerfile<br>├── observability/<br>│   ├── docker-compose.yml<br>│   ├── prometheus/<br>│   │   ├── prometheus.yml<br>│   │   └── rules.yml<br>│   ├── alertmanager/<br>│   │   └── alertmanager.yml<br>│   ├── alert-receiver/<br>│   │   ├── receiver.py<br>│   │   └── Dockerfile<br>│   └── grafana/<br>│       ├── provisioning/<br>│       │   └── datasources/<br>│       │       └── datasource.yml<br>│       └── dashboards/<br>│           └── README.md<br>├── logging/<br>│   └── fluent-bit/<br>│       ├── fluent-bit.conf<br>│       └── parsers.conf<br>├── runbooks/<br>│   ├── ALERT-service-down.md<br>│   ├── ALERT-high-5xx.md<br>│   ├── ALERT-high-latency.md<br>│   └── ALERT-disk-full.md<br>├── postmortems/<br>│   ├── template.md<br>│   ├── PM-incident-5xx-spike.md<br>│   └── PM-incident-latency-spike.md<br>├── scripts/<br>│   ├── generate_5xx.sh<br>│   ├── generate_latency.sh<br>│   └── load_normal.sh<br>├── docs/<br>│   ├── sev-definitions.md<br>│   ├── oncall-escalation.md<br>│   └── demo-script.md<br>└── .gitignore</pre><p>With this repo, you’re not just shipping code; you’re shipping operations.</p><h3>Step 2: Terraform on AWS (IaaS VM with Secure Networking)</h3><p>Reliability starts with an infrastructure you can reproduce securely.</p><p>This step provisions a single Ubuntu EC2 instance with a security group that:</p><ul><li>Allows SSH access only from your IP</li><li>Exposes the app publicly on port 80</li><li>Restricts Grafana, Prometheus, Alertmanager, and OpenSearch Dashboards to your IP</li></ul><h4>2.1 terraform/variables.tf</h4><pre>variable &quot;region&quot; {<br>  type    = string<br>  default = &quot;ap-south-1&quot;<br>}<br><br>variable &quot;instance_type&quot; {<br>  type    = string<br>  default = &quot;t3.small&quot;<br>}<br><br>variable &quot;key_name&quot; {<br>  type = string<br>  default = &quot;sre-mini-key&quot;<br>}<br><br>variable &quot;my_ip_cidr&quot; {<br>  type        = string<br>  description = &quot;Your public IP in CIDR form, example: 1.2.3.4/32. Check first at, curl -s https://checkip.amazonaws.com&quot;<br>  default = &quot;103.48.199.122/32&quot;<br>}<br><br>variable &quot;app_port&quot; {<br>  type    = number<br>  default = 80<br>}</pre><h4>2.2 terraform/user_data.sh</h4><p>This shell script installs Docker and sets up the required directories:</p><pre>#!/bin/bash<br>set -eux<br><br>apt-get update<br>apt-get install -y ca-certificates curl gnupg unzip<br><br>install -m 0755 -d /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg<br>chmod a+r /etc/apt/keyrings/docker.gpg<br><br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; \<br>  &gt; /etc/apt/sources.list.d/docker.list<br><br>apt-get update<br>apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin<br><br>usermod -aG docker ubuntu<br><br>mkdir -p /opt/sre-mini/{app,observability,logging,runbooks,postmortems,scripts}<br>chmod -R 755 /opt/sre-mini</pre><h4>2.3 terraform/main.tf</h4><p>This provisions the EC2 instance and configures its security group.</p><p>Notice the deliberate exposure model:</p><ul><li>Port 80 is public (app)</li><li>Ports 3000, 9090, 9093, and 5601 are restricted to your IP address</li><li>OpenSearch 9200 is not opened publicly and is bound to localhost in Docker</li></ul><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = var.region<br>}<br><br>data &quot;aws_ami&quot; &quot;ubuntu&quot; {<br>  most_recent = true<br>  owners      = [&quot;099720109477&quot;] # Canonical<br><br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*&quot;]<br>  }<br>}<br><br>resource &quot;aws_security_group&quot; &quot;sre_sg&quot; {<br>  name        = &quot;sre-mini-prod-sg&quot;<br>  description = &quot;SRE mini prod SG&quot;<br><br>  ingress {<br>    description = &quot;SSH from my IP only&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [var.my_ip_cidr]<br>  }<br><br>  ingress {<br>    description = &quot;Public web app&quot;<br>    from_port   = var.app_port<br>    to_port     = var.app_port<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  # Observability UI ports restricted to your IP<br>  ingress {<br>    description = &quot;Grafana&quot;<br>    from_port   = 3000<br>    to_port     = 3000<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [var.my_ip_cidr]<br>  }<br><br>  ingress {<br>    description = &quot;Prometheus&quot;<br>    from_port   = 9090<br>    to_port     = 9090<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [var.my_ip_cidr]<br>  }<br><br>  ingress {<br>    description = &quot;Alertmanager&quot;<br>    from_port   = 9093<br>    to_port     = 9093<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [var.my_ip_cidr]<br>  }<br><br>  ingress {<br>    description = &quot;OpenSearch Dashboards&quot;<br>    from_port   = 5601<br>    to_port     = 5601<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [var.my_ip_cidr]<br>  }<br><br>  # OpenSearch itself should not be open publicly, but we bind it to localhost in docker.<br>  # If you do expose it, restrict to your IP only.<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}<br><br>resource &quot;aws_instance&quot; &quot;sre_vm&quot; {<br>  ami                    = data.aws_ami.ubuntu.id<br>  instance_type          = var.instance_type<br>  key_name               = var.key_name<br>  vpc_security_group_ids = [aws_security_group.sre_sg.id]<br><br>  user_data = file(&quot;${path.module}/user_data.sh&quot;)<br><br>  root_block_device {<br>    volume_size = 30<br>    volume_type = &quot;gp3&quot;<br>  }<br><br>  tags = {<br>    Name = &quot;sre-mini-prod&quot;<br>  }<br>}</pre><h4>2.4 terraform/outputs.tf</h4><pre>output &quot;public_ip&quot; {<br>  value = aws_instance.sre_vm.public_ip<br>}<br><br>output &quot;ssh_command&quot; {<br>  value = &quot;ssh -i ~/.ssh/&lt;YOUR_KEY.pem&gt; ubuntu@${aws_instance.sre_vm.public_ip}&quot;<br>}<br><br>output &quot;app_url&quot; {<br>  value = &quot;http://${aws_instance.sre_vm.public_ip}/&quot;<br>}<br><br>output &quot;grafana_url&quot; {<br>  value = &quot;http://${aws_instance.sre_vm.public_ip}:3000/&quot;<br>}<br><br>output &quot;prometheus_url&quot; {<br>  value = &quot;http://${aws_instance.sre_vm.public_ip}:9090/&quot;<br>}<br><br>output &quot;opensearch_dashboards_url&quot; {<br>  value = &quot;http://${aws_instance.sre_vm.public_ip}:5601/&quot;<br>}</pre><h4>2.5 Apply Terraform</h4><p>From repo root, initialize and apply Terraform:</p><pre>cd terraform<br>terraform init<br><br>terraform plan<br><br>terraform apply \<br>  -var=&quot;key_name=sre-mini-key&quot; \<br>  -var=&quot;my_ip_cidr=$(curl -s https://checkip.amazonaws.com)/32&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*c2GWvBo0v3V5tPgVpaUNLA.png" /><figcaption>Fig: Terraform Output</figcaption></figure><p>Copy the public IP output, then SSH into the instance:</p><pre>ssh -i ~/.ssh/path/to/&lt;YOUR_KEY.pem&gt; ubuntu@&lt;PUBLIC_IP&gt;<br><br># Example<br>ssh -i ~/.ssh/sre-mini-key.pem ubuntu@3.109.212.138</pre><h3>Step 3: Build the Demo Web Service (Flask + Prometheus Metrics)</h3><p>SRE practices require a service that is both observable and capable of failing on demand. This Flask-based web service does exactly that. It includes:</p><ul><li>/healthz: health check</li><li>/metrics: Prometheus metrics endpoint</li><li>/error: always returns HTTP 500 to simulate failure</li><li>/work?ms=2000: injects latency by sleeping for the given number of milliseconds</li></ul><p>Logs are emitted in JSON format to both stdout and a local file, enabling ingestion by Fluent Bit to ship into OpenSearch.</p><h4>3.1 app/requirements.txt</h4><pre>flask==3.0.3<br>prometheus-client==0.20.0<br>gunicorn==22.0.0</pre><h4>3.2 app/app.py</h4><pre>import json<br>import os<br>import random<br>import time<br>from datetime import datetime<br>from flask import Flask, request, Response<br><br>from prometheus_client import Counter, Histogram, generate_latest, CONTENT_TYPE_LATEST<br><br>APP_NAME = &quot;sre-mini-service&quot;<br>LOG_PATH = os.environ.get(&quot;APP_LOG_PATH&quot;, &quot;/var/log/app/app.log&quot;)<br><br>app = Flask(__name__)<br><br>REQUESTS = Counter(<br>    &quot;http_requests_total&quot;,<br>    &quot;Total HTTP requests&quot;,<br>    [&quot;method&quot;, &quot;path&quot;, &quot;status&quot;]<br>)<br><br>LATENCY = Histogram(<br>    &quot;http_request_latency_seconds&quot;,<br>    &quot;Request latency in seconds&quot;,<br>    [&quot;path&quot;],<br>    buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0)<br>)<br><br>def write_log(level: str, message: str, **fields):<br>  record = {<br>      &quot;ts&quot;: datetime.utcnow().isoformat() + &quot;Z&quot;,<br>      &quot;level&quot;: level,<br>      &quot;service&quot;: APP_NAME,<br>      &quot;message&quot;: message,<br>      &quot;path&quot;: request.path if request else None,<br>      &quot;method&quot;: request.method if request else None,<br>      &quot;remote_addr&quot;: request.remote_addr if request else None,<br>      **fields<br>  }<br>  line = json.dumps(record, separators=(&quot;,&quot;, &quot;:&quot;))<br>  print(line, flush=True)<br>  try:<br>      os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)<br>      with open(LOG_PATH, &quot;a&quot;, encoding=&quot;utf-8&quot;) as f:<br>          f.write(line + &quot;\n&quot;)<br>  except Exception:<br>      pass<br><br>@app.before_request<br>def start_timer():<br>    request._start_time = time.time()<br><br>@app.after_request<br>def record_metrics(response):<br>    elapsed = time.time() - getattr(request, &quot;_start_time&quot;, time.time())<br>    LATENCY.labels(path=request.path).observe(elapsed)<br>    REQUESTS.labels(method=request.method, path=request.path, status=str(response.status_code)).inc()<br>    write_log(&quot;info&quot;, &quot;request_completed&quot;, status=response.status_code, latency_ms=int(elapsed * 1000))<br>    return response<br><br>@app.get(&quot;/healthz&quot;)<br>def healthz():<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;service&quot;: APP_NAME}, 200<br><br>@app.get(&quot;/metrics&quot;)<br>def metrics():<br>    return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)<br><br>@app.get(&quot;/&quot;)<br>def home():<br>    return {&quot;hello&quot;: &quot;sre-mini-prod&quot;, &quot;try&quot;: [&quot;/healthz&quot;, &quot;/work?ms=2000&quot;, &quot;/error&quot;, &quot;/metrics&quot;]}, 200<br><br>@app.get(&quot;/error&quot;)<br>def error():<br>    # Always generate a 500, but also log an explicit error event<br>    write_log(&quot;error&quot;, &quot;intentional_error_triggered&quot;, reason=&quot;demo_endpoint&quot;)<br>    return {&quot;error&quot;: &quot;intentional 500 for alert testing&quot;}, 500<br><br>@app.get(&quot;/work&quot;)<br>def work():<br>    # Latency injection, ms can be large to trigger p95 alerts<br>    ms = int(request.args.get(&quot;ms&quot;, &quot;200&quot;))<br>    jitter = random.randint(0, 50)<br>    sleep_s = (ms + jitter) / 1000.0<br>    time.sleep(sleep_s)<br>    return {&quot;ok&quot;: True, &quot;slept_ms&quot;: ms + jitter}, 200<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=8080)</pre><h4>3.3 app/Dockerfile</h4><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY app.py .<br><br>ENV APP_LOG_PATH=/var/log/app/app.log<br>EXPOSE 8080<br><br>CMD [&quot;gunicorn&quot;, &quot;-b&quot;, &quot;0.0.0.0:8080&quot;, &quot;--workers&quot;, &quot;2&quot;, &quot;--threads&quot;, &quot;4&quot;, &quot;app:app&quot;]</pre><h3>Step 4: Deploy the Full Stack on the VM (Docker Compose)</h3><p>Once your app is containerized, you’ll use Docker Compose to bring up the full observability stack on your EC2 VM.</p><p>This includes:</p><ul><li>The Flask web app (port 80)</li><li>Prometheus (port 9090)</li><li>Grafana (port 3000)</li><li>Alertmanager (port 9093)</li><li>Node Exporter (host metrics)</li><li>Alert Receiver (simulates paging)</li><li>OpenSearch and OpenSearch Dashboards</li><li>Fluent Bit for log shipping</li></ul><h4>4.1 observability/docker-compose.yml</h4><pre>services:<br>  app:<br>    build: ../app<br>    container_name: sre_app<br>    ports:<br>      - &quot;80:8080&quot;<br>    volumes:<br>      - app_logs:/var/log/app<br>    restart: unless-stopped<br><br>  node-exporter:<br>    image: prom/node-exporter:v1.8.2<br>    container_name: node_exporter<br>    pid: host<br>    network_mode: host<br>    command:<br>      - &quot;--path.rootfs=/host&quot;<br>    volumes:<br>      - &quot;/:/host:ro,rslave&quot;<br>    restart: unless-stopped<br><br>  prometheus:<br>    image: prom/prometheus:v2.54.1<br>    container_name: prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro<br>      - ./prometheus/rules.yml:/etc/prometheus/rules.yml:ro<br>      - prom_data:/prometheus<br>    command:<br>      - &quot;--config.file=/etc/prometheus/prometheus.yml&quot;<br>    restart: unless-stopped<br>    depends_on:<br>      - app<br>      - alertmanager<br><br>  alertmanager:<br>    image: prom/alertmanager:v0.27.0<br>    container_name: alertmanager<br>    ports:<br>      - &quot;9093:9093&quot;<br>    volumes:<br>      - ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro<br>    command:<br>      - &quot;--config.file=/etc/alertmanager/alertmanager.yml&quot;<br>    restart: unless-stopped<br>    depends_on:<br>      - alert-receiver<br><br>  alert-receiver:<br>    build: ./alert-receiver<br>    container_name: alert_receiver<br>    ports:<br>      - &quot;5001:5001&quot;<br>    restart: unless-stopped<br><br>  grafana:<br>    image: grafana/grafana:11.1.4<br>    container_name: grafana<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - GF_SECURITY_ADMIN_USER=admin<br>      - GF_SECURITY_ADMIN_PASSWORD=admin123<br>    volumes:<br>      - grafana_data:/var/lib/grafana<br>      - ./grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro<br>    restart: unless-stopped<br>    depends_on:<br>      - prometheus<br><br>  opensearch:<br>    image: opensearchproject/opensearch:2.17.1<br>    container_name: opensearch<br>    environment:<br>      - discovery.type=single-node<br>      - plugins.security.disabled=true<br>      - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m<br>    ulimits:<br>      memlock: { soft: -1, hard: -1 }<br>      nofile: { soft: 65536, hard: 65536 }<br>    ports:<br>      - &quot;127.0.0.1:9200:9200&quot;<br>    volumes:<br>      - os_data:/usr/share/opensearch/data<br>    restart: unless-stopped<br><br>  opensearch-dashboards:<br>    image: opensearchproject/opensearch-dashboards:2.17.1<br>    container_name: os_dashboards<br>    environment:<br>      - OPENSEARCH_HOSTS=[&quot;http://opensearch:9200&quot;]<br>      - DISABLE_SECURITY_DASHBOARDS_PLUGIN=true<br>    ports:<br>      - &quot;5601:5601&quot;<br>    restart: unless-stopped<br>    depends_on:<br>      - opensearch<br><br>  fluent-bit:<br>    image: fluent/fluent-bit:3.1.8<br>    container_name: fluent_bit<br>    volumes:<br>      - app_logs:/var/log/app:ro<br>      - ../logging/fluent-bit/fluent-bit.conf:/fluent-bit/etc/fluent-bit.conf:ro<br>      - ../logging/fluent-bit/parsers.conf:/fluent-bit/etc/parsers.conf:ro<br>    restart: unless-stopped<br>    depends_on:<br>      - opensearch<br><br>volumes:<br>  prom_data:<br>  grafana_data:<br>  os_data:<br>  app_logs:</pre><h4>4.2 Copy the repo to the VM and run</h4><p>On your local machine:</p><pre># From repo root<br>scp -i /path/to/&lt;YOUR_KEY.pem&gt; -r . ubuntu@PUBLIC_IP:/home/ubuntu/sre-mini-prod-aws<br><br># Example<br>scp -i ~/.ssh/sre-mini-key.pem -r \<br>  app observability logging scripts runbooks postmortems docs README.md .gitignore \<br>  ubuntu@3.109.212.138:/home/ubuntu/sre-mini-prod-aws</pre><blockquote>Note: <br>1. Make sure your aws login is not expired.<br>2. In the next step when you will run “docker compose” you will get errors, because though we have created the complete docker-compose.yml, we have still not created the required files for the containers. Temporary solution is to comment out all the containers except “app”.</blockquote><p>On the VM:</p><pre>cd ~/sre-mini-prod-aws/observability<br>docker compose up -d --build<br>docker ps --format &quot;table {{.Names}}\t{{.Status}}\t{{.Ports}}&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mu5oBZ-XH6qJF3ERo_8qhw.png" /><figcaption>Fig: docker ps output</figcaption></figure><p>Quick local tests (from VM):</p><pre>curl -s http://localhost/healthz<br>curl -s http://localhost/metrics | head</pre><p>From your browser (Expected while all the “observability” files are completed):</p><ul><li>App: <a href="http://public_ip/">http://PUBLIC_IP/</a> (Currently, this will only work)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opo03Nhh_8AyJtz_JwyScg.png" /><figcaption>Fig: <a href="http://public_ip/">http://PUBLIC_IP/</a></figcaption></figure><ul><li>Prometheus: http://PUBLIC_IP:9090/ (restricted to your IP)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiFmspBybzsmGOi9DsPXNQ.png" /><figcaption>Fig: <a href="http://public_ip:9090/">http://PUBLIC_IP:9090/</a></figcaption></figure><ul><li>Grafana: http://PUBLIC_IP:3000/ (restricted, login admin / admin123)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz6QPoU83Nys3rGzmV4B-g.png" /><figcaption>Fig: <a href="http://public_ip:3000/">http://PUBLIC_IP:3000/</a></figcaption></figure><ul><li>OpenSearch Dashboards: http://PUBLIC_IP:5601/ (restricted)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFjpBgncpszb7uTSPwySLw.png" /><figcaption>Fig: <a href="http://public_ip:5601/">http://PUBLIC_IP:5601/</a></figcaption></figure><h3>Step 5: Prometheus Scraping Configuration</h3><p>Prometheus is only useful if it can reliably scrape your targets. You will scrape:</p><ul><li>The app at app:8080 (inside Docker network)</li><li>Node Exporter on the VM itself (host metrics)</li></ul><h4>5.1 observability/prometheus/prometheus.yml</h4><p>Start with:</p><pre>global:<br>  scrape_interval: 15s<br>  evaluation_interval: 15s<br><br>alerting:<br>  alertmanagers:<br>    - static_configs:<br>        - targets: [&quot;alertmanager:9093&quot;]<br><br>rule_files:<br>  - /etc/prometheus/rules.yml<br><br>scrape_configs:<br>  - job_name: &quot;app&quot;<br>    static_configs:<br>      - targets: [&quot;app:8080&quot;]<br>    metrics_path: /metrics<br><br>  - job_name: &quot;node&quot;<br>    static_configs:<br>      - targets: [&quot;172.31.12.158:9100&quot;] # or [&quot;VM_PRIVATE_IP:9100&quot;] or [&quot;host.docker.internal:9100&quot;]</pre><blockquote>On Linux, host.docker.internal often does not resolve. Since Node Exporter is running with network_mode: host, it is reachable at the VM’s IP on port 9100.</blockquote><p>Find the VM private IP:</p><pre>hostname -I</pre><p>Update the Node target:</p><pre>  - job_name: &quot;node&quot;<br>    static_configs:<br>      - targets: [&quot;PRIVATE_IP:9100&quot;]</pre><blockquote>Note: Uncomment the “Prometheus” and “Node Exporter” container from our “docker-compose.yml”.</blockquote><h3>Step 6: Grafana Datasource and Dashboards</h3><p>Grafana makes metrics actionable. Here you will:</p><ul><li>Provision a Prometheus datasource automatically (no manual clicking needed for the datasource)</li><li>Build two dashboards manually</li><li>Commit all PromQL used in panels to the repo</li></ul><h4>6.1 observability/grafana/provisioning/datasources/datasource.yml</h4><pre>apiVersion: 1<br><br>datasources:<br>  - name: Prometheus<br>    type: prometheus<br>    access: proxy<br>    url: http://prometheus:9090<br>    isDefault: true</pre><h4>6.2 Building Dashboards</h4><p>Create these dashboards manually in Grafana UI (<a href="http://public_ip:3000/">http://PUBLIC_IP:3000/</a>). Then store the exact PromQL in:</p><ul><li>observability/grafana/dashboards/README.md</li></ul><p><strong>Dashboard A: Golden Signals</strong></p><p>Golden Signals are a clean, SRE-friendly way to see reliability and user impact:</p><ul><li>Traffic (are users hitting us?)</li><li>Errors (are users failing?)</li><li>Latency (are users waiting?)</li><li>Saturation (are we running out of resources?)</li></ul><p>Panels and PromQL:</p><ul><li>Traffic (RPS):</li></ul><pre>sum(rate(http_requests_total[5m]))<br><br>Unit: requests/sec (Grafana unit: req/s or ops/s)</pre><ul><li>Errors (5xx rate):</li></ul><pre>sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br><br>Unit: requests/sec (req/s)</pre><ul><li>5xx Error ratio:</li></ul><pre>#1 <br><br>sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>/<br>sum(rate(http_requests_total[5m]))<br><br>Unit option A: ratio (Grafana unit: none)<br><br>#2: If you want percent (0–100), use this instead<br><br>100 *<br>(<br>  sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>  /<br>  sum(rate(http_requests_total[5m]))<br>)<br><br>Unit option B: Percent (0–100)</pre><ul><li>Latency p95 (seconds):</li></ul><pre>#1<br><br>histogram_quantile(<br>  0.95,<br>  sum by (le) (rate(http_request_latency_seconds_bucket[5m]))<br>)<br><br>Unit: seconds (s)<br><br>#2 If you prefer milliseconds in Grafana, multiply by 1000:<br><br>1000 *<br>histogram_quantile(<br>  0.95,<br>  sum by (le) (rate(http_request_latency_seconds_bucket[5m]))<br>)<br><br>Unit: milliseconds (ms)</pre><ul><li>Saturation (CPU %):</li></ul><pre>100 * (1 - avg(rate(node_cpu_seconds_total{mode=&quot;idle&quot;}[5m])))<br><br>Unit: Percent (0–100)</pre><ul><li>Saturation (Memory %)</li></ul><pre>100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))<br><br>Unit: Percent (0–100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqAaN1mjvfNE0uLEMeOeaw.png" /><figcaption>Fig: Dashboard A</figcaption></figure><p><strong>Dashboard B: Host dashboard</strong></p><p>This dashboard answers: “Is the machine healthy?”</p><ul><li>CPU percent:</li></ul><pre>100 * (1 - avg(rate(node_cpu_seconds_total{mode=&quot;idle&quot;}[5m])))<br><br>Unit: Percent (0–100)</pre><ul><li>Memory percent:</li></ul><pre>100 * (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes))<br><br>Unit: Percent (0–100) </pre><ul><li>Disk/percent used (Disk root filesystem percent used):</li></ul><pre>100 * (1 - (node_filesystem_avail_bytes{mountpoint=&quot;/&quot;} / node_filesystem_size_bytes{mountpoint=&quot;/&quot;}))<br><br>Unit: Percent (0–100)<br><br># If you see duplicates because of multiple devices/filesystems, use this safer variant:<br>100 * (1 - (<br>  max by (instance) (node_filesystem_avail_bytes{mountpoint=&quot;/&quot;,fstype!~&quot;tmpfs|overlay&quot;})<br>  /<br>  max by (instance) (node_filesystem_size_bytes{mountpoint=&quot;/&quot;,fstype!~&quot;tmpfs|overlay&quot;})<br>))</pre><ul><li>Network RX (B/s) (Network receive bytes per second):</li></ul><pre>sum(rate(node_network_receive_bytes_total[5m]))<br><br>Unit: bytes/sec (Grafana unit: B/s)<br><br># Optional improvement to exclude loopback:<br>sum(rate(node_network_receive_bytes_total{device!=&quot;lo&quot;}[5m]))</pre><ul><li>Network TX (B/s) (Network transmit bytes per second):</li></ul><pre>sum(rate(node_network_transmit_bytes_total[5m]))<br><br>Unit: bytes/sec (B/s) <br><br># Optional improvement:<br>sum(rate(node_network_transmit_bytes_total{device!=&quot;lo&quot;}[5m]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQwisaRiRP73i-JooGI-nw.png" /><figcaption>Dashboard B</figcaption></figure><h3>Step 7: Define SLOs and Error Budgets</h3><p>Dashboards show what is happening, but SRE decisions are driven by SLOs.</p><ul><li>SLI: a measurable indicator (success rate, p95 latency)</li><li>SLO: a target for that indicator (99.9%, p95 &lt; 250ms)</li><li>Error budget: allowed unreliability (what you can “spend” before you must slow down change)</li></ul><h4>7.1 Define SLOs</h4><p>Use these portfolio SLO statements:</p><ul><li>Availability SLO: 99.9% successful requests over 30 days<br> Success means HTTP status is not 5xx.</li><li>Latency SLO: p95 latency under 0.25s over 30 days<br> This is intentionally strict, so your latency injection can violate it.</li></ul><h4>7.2 SLIs in PromQL</h4><ul><li>Availability SLI (success ratio)</li></ul><pre>1 - (<br>  sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>  /<br>  sum(rate(http_requests_total[5m]))<br>)</pre><ul><li>Latency p95 SLI</li></ul><pre>histogram_quantile(<br>  0.95,<br>  sum by (le) (rate(http_request_latency_seconds_bucket[5m]))<br>)</pre><h4>7.3 Error budget explanation</h4><p>If the availability SLO is 99.9% over 30 days, allowed failure is 0.1%. That 0.1% is the error budget.</p><p>When you burn that budget too fast, you alert. This keeps alerts tied to user impact instead of random thresholds.</p><p>A clean SRE pattern is:</p><ul><li>fast burn triggers a page (critical)</li><li>slow burn creates a ticket (warning)</li></ul><p>This project uses severity routing to represent that difference.</p><h3>Step 8: Alerting (Prometheus rules + Alertmanager routing)</h3><p>Alerts are for situations that require action. Here you will:</p><ul><li>Define alert rules in Prometheus</li><li>Route alerts by severity in Alertmanager</li><li>Deliver alerts to a local webhook receiver (simulated on-call)</li></ul><h4>8.1 observability/prometheus/rules.yml</h4><p>Define alert rules like:</p><ul><li>App down</li><li>High 5xx error ratio</li><li>High p95 latency</li><li>Disk usage &gt; 85%</li></ul><p>Each rule includes severity (warning/critical).</p><pre>groups:<br>  - name: sre-mini-alerts<br>    rules:<br>      - alert: ServiceDown<br>        expr: up{job=&quot;app&quot;} == 0<br>        for: 1m<br>        labels:<br>          severity: critical<br>        annotations:<br>          summary: &quot;Service is down&quot;<br>          description: &quot;Prometheus cannot scrape the app for 1 minute.&quot;<br><br>      - alert: High5xxErrorRatio<br>        expr: |<br>          (<br>            sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>            /<br>            sum(rate(http_requests_total[5m]))<br>          ) &gt; 0.05<br>        for: 2m<br>        labels:<br>          severity: critical<br>        annotations:<br>          summary: &quot;High 5xx error ratio&quot;<br>          description: &quot;5xx ratio &gt; 5% for 2 minutes.&quot;<br><br>      - alert: HighLatencyP95<br>        expr: |<br>          histogram_quantile(<br>            0.95,<br>            sum by (le) (rate(http_request_latency_seconds_bucket[5m]))<br>          ) &gt; 0.25<br>        for: 3m<br>        labels:<br>          severity: warning<br>        annotations:<br>          summary: &quot;High p95 latency&quot;<br>          description: &quot;p95 latency &gt; 250ms for 3 minutes.&quot;<br><br>      - alert: DiskFillingUpRoot<br>        expr: |<br>          (1 - (node_filesystem_avail_bytes{mountpoint=&quot;/&quot;} / node_filesystem_size_bytes{mountpoint=&quot;/&quot;})) &gt; 0.85<br>        for: 5m<br>        labels:<br>          severity: warning<br>        annotations:<br>          summary: &quot;Disk usage high on /&quot;<br>          description: &quot;Root filesystem &gt; 85% for 5 minutes.&quot;</pre><h4>8.2 Alertmanager, route based on severity:</h4><p>Path: observability/alertmanager/alertmanager.yml</p><pre>route:<br>  receiver: &quot;oncall-warning&quot;<br>  group_by: [&quot;alertname&quot;]<br>  group_wait: 10s<br>  group_interval: 1m<br>  repeat_interval: 30m<br><br>  routes:<br>    - matchers:<br>        - severity=&quot;critical&quot;<br>      receiver: &quot;oncall-critical&quot;<br>      repeat_interval: 5m<br><br>receivers:<br>  - name: &quot;oncall-warning&quot;<br>    webhook_configs:<br>      - url: &quot;http://alert-receiver:5001/alerts&quot;<br>        send_resolved: true<br><br>  - name: &quot;oncall-critical&quot;<br>    webhook_configs:<br>      - url: &quot;http://alert-receiver:5001/alerts&quot;<br>        send_resolved: true</pre><h4>8.3 Alert receiver (simulated on-call sink)</h4><p>This is your “paging output.” It prints Alertmanager payloads as JSON.</p><p>Path: observability/alert-receiver/receiver.py</p><pre>from flask import Flask, request<br>import json<br>from datetime import datetime<br><br>app = Flask(__name__)<br><br>@app.post(&quot;/alerts&quot;)<br>def alerts():<br>    payload = request.get_json(force=True, silent=True)<br>    print(json.dumps({<br>        &quot;ts&quot;: datetime.utcnow().isoformat() + &quot;Z&quot;,<br>        &quot;type&quot;: &quot;alertmanager_event&quot;,<br>        &quot;payload&quot;: payload<br>    }, separators=(&quot;,&quot;, &quot;:&quot;)), flush=True)<br>    return {&quot;ok&quot;: True}, 200<br><br>@app.get(&quot;/healthz&quot;)<br>def healthz():<br>    return {&quot;ok&quot;: True}, 200<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(host=&quot;0.0.0.0&quot;, port=5001)</pre><p>Path: observability/alert-receiver/Dockerfile</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br>RUN pip install flask==3.0.3<br>COPY receiver.py .<br>EXPOSE 5001<br>CMD [&quot;python&quot;, &quot;receiver.py&quot;]</pre><blockquote>Uncomment “alertmanager” and “alert-receiver” from our “docker-compose.yml”</blockquote><h4>8.4 On-call escalation note</h4><p>Create docs/oncall-escalation.md with this policy:</p><ul><li>Warning alerts create a ticket and are handled in business hours</li><li>critical alerts page immediately, require ack, mitigation within 15 minutes</li><li>If not mitigated, escalate to secondary on-call after 10 minutes</li><li>after mitigation: declare resolved, start postmortem if SEV1/SEV2</li></ul><h3>Step 9: Logging Pipeline (Fluent Bit + OpenSearch)</h3><p>Metrics tell you what broke. Logs help you understand why.</p><p>This logging pipeline does the following:</p><ul><li>The app writes JSON logs to /var/log/app/app.log (inside a Docker volume)</li><li>Fluent Bit tails that file and ships logs into OpenSearch</li><li>OpenSearch Dashboards lets you search and build incident evidence timelines</li></ul><h4>9.1 Fluent Bit config</h4><p>Path: logging/fluent-bit/parsers.conf</p><pre>[PARSER]<br>    Name   json<br>    Format json<br>    Time_Key ts<br>    Time_Format %Y-%m-%dT%H:%M:%S.%LZ</pre><p>Path: logging/fluent-bit/fluent-bit.conf</p><pre>[SERVICE]<br>    Flush        1<br>    Log_Level    info<br>    Parsers_File /fluent-bit/etc/parsers.conf<br><br>[INPUT]<br>    Name   tail<br>    Path   /var/log/app/app.log<br>    Parser json<br>    Tag    app.log<br><br>[FILTER]<br>    Name   modify<br>    Match  app.log<br>    Add    env demo<br><br>[OUTPUT]<br>    Name  opensearch<br>    Match app.log<br>    Host  opensearch<br>    Port  9200<br>    Index sre-mini-logs<br>    Type  _doc<br>    Suppress_Type_Name On</pre><blockquote>Uncomment “node-exporter”, “opensearch”, “opensearch-dashboards”, “fluent-bit” from out “docker-compose.yml”</blockquote><pre>&quot;&quot;&quot;<br>Note: <br><br>1. Make sure your aws login is not expired.<br>```<br>unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN<br>unset AWS_PROFILE AWS_DEFAULT_REGION AWS_REGION<br><br>aws login --profile sre-mini --region ap-south-1<br>```<br>2. Export fresh credentials into your shell<br>```<br>eval &quot;$(aws configure export-credentials --profile sre-mini --format env)&quot;<br><br>export AWS_REGION=ap-south-1<br>export AWS_DEFAULT_REGION=ap-south-1<br>export AWS_EC2_METADATA_DISABLED=true<br>```<br>3. Verify the exported creds work<br>```<br>aws sts get-caller-identity --region ap-south-1<br>```<br>4. Update the security group rule with new IP via Terraform:<br>```<br>terraform apply -var=&quot;key_name=sre-mini-key&quot; -var=&quot;my_ip_cidr=$(curl -s https://checkip.amazonaws.com)/32&quot;<br>```<br>&quot;&quot;&quot;<br><br># Copy the repo to the VM and run<br>## From repo root<br>scp -i /path/to/&lt;YOUR_KEY.pem&gt; -r . ubuntu@PUBLIC_IP:/home/ubuntu/sre-mini-prod-aws<br><br>## Example<br>scp -i ~/.ssh/sre-mini-key.pem -r \<br>  app observability logging scripts runbooks postmortems docs README.md .gitignore \<br>  ubuntu@3.109.212.138:/home/ubuntu/sre-mini-prod-aws<br><br># On the VM<br>cd ~/sre-mini-prod-aws/observability<br>docker compose up -d --build<br>docker ps --format &quot;table {{.Names}}\t{{.Status}}\t{{.Ports}}&quot;<br><br># Output [curl -s https://checkip.amazonaws.com]<br>App: http://PUBLIC_IP/ <br>Prometheus: http://PUBLIC_IP:9090/ (restricted to your IP)<br>Grafana: http://PUBLIC_IP:3000/ (restricted, login admin / admin123)<br>OpenSearch Dashboards: http://PUBLIC_IP:5601/ (restricted)</pre><h4>9.2 Verify logs are flowing</h4><p>Generate traffic from the VM:</p><pre>curl -s http://localhost/<br>curl -s http://localhost/error<br>curl -s &quot;http://localhost/work?ms=800&quot;</pre><p>In OpenSearch Dashboards:</p><ul><li>Go to Discover</li><li>Create index pattern: sre-mini-logs*</li><li>Time field: Select it</li></ul><h4>9.3 Practical incident queries (OpenSearch KQL style, in Discover search bar)</h4><p>These are the kinds of queries you use during a real incident.</p><ul><li>All 5xx evidence</li></ul><pre>message: &quot;request_completed&quot; AND path: &quot;/work&quot;</pre><ul><li>Latency evidence</li></ul><pre>latency_ms &gt;= 500</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8lIVTZA1chTaQz14_1Trg.png" /><figcaption>Fig: Latency evidence</figcaption></figure><ul><li>Impact window for incident timeline</li></ul><pre>message: &quot;request_completed&quot; AND path: &quot;/work&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRO5SnF4j3i-8hZUb5KTfQ.png" /><figcaption>Fig: Impact window for incident timeline</figcaption></figure><h3>Step 10: Incident response package (SEVs, runbooks, postmortems)</h3><p>This is where this project becomes “SRE-grade.” You are not just monitoring, you are showing how to respond consistently under pressure.</p><h4>10.1 Severity definitions</h4><p>Create docs/sev-definitions.md:</p><ul><li>SEV1: Service down or severe user impact, paging, immediate response</li><li>SEV2: Partial degradation (high errors or high latency), urgent response</li><li>SEV3: Minor issue, workaround exists, handle in business hours</li></ul><h4>10.2 Runbooks/SOPs (one per major alert)</h4><p>You will create one runbook per major alert:</p><ul><li>runbooks/ALERT-service-down.md</li><li>runbooks/ALERT-high-5xx.md</li><li>runbooks/ALERT-high-latency.md</li><li>runbooks/ALERT-disk-full.md</li></ul><p>Below are complete, runnable contents for each file.</p><p>Path: runbooks/ALERT-service-down.md</p><pre># Runbook: ServiceDown (severity=critical)<br><br>## What it means<br>Prometheus cannot scrape the app target for at least 1 minute. The service may be down or unreachable.<br><br>## User impact<br>Potential full outage (requests may fail or time out).<br><br>## Immediate actions (first 5 minutes)<br>1) Confirm the symptom:<br>- Grafana Golden Signals: Traffic drop, Errors may spike.<br>- Prometheus Targets: app target may show DOWN.<br><br>2) Check container status on the VM:<br>```bash<br>docker ps<br>docker logs --tail=200 sre_app<br>````<br><br>3. Confirm the service locally on the VM:<br><br>```bash<br>curl -sv http://localhost/healthz<br>curl -sv http://localhost/metrics | head<br>```<br><br>## Likely causes<br><br>* App container crashed or exited.<br>* Docker daemon issues.<br>* Resource exhaustion (CPU/memory/disk).<br>* Prometheus scrape misconfiguration.<br><br>## Mitigation steps<br><br>1. Restart the app container:<br><br>```bash<br>docker restart sre_app<br>```<br><br>2. If that fails, rebuild the stack:<br><br>```bash<br>cd ~/sre-mini-prod-aws/observability<br>docker compose up -d --build<br>```<br><br>3. If Prometheus is the only failing component, restart Prometheus:<br><br>```bash<br>docker restart prometheus<br>```<br><br>## Rollback steps<br><br>* If a recent change broke the service, revert the repo to the last known good commit and redeploy:<br><br>```bash<br>cd ~/sre-mini-prod-aws<br>git log --oneline -n 10<br># git checkout &lt;known_good_commit&gt;<br>cd observability<br>docker compose up -d --build<br>```<br><br>## Verify recovery<br><br>* Prometheus Targets: app is UP.<br>* Health check returns 200:<br><br>```bash<br>curl -s http://localhost/healthz<br>```<br><br>* Traffic returns on Grafana.</pre><p>Path: runbooks/ALERT-high-latency.md</p><pre># Runbook: HighLatencyP95 (severity=warning)<br><br>## What it means<br>p95 latency is above 250ms for 3 minutes. Users are experiencing slow responses.<br><br>## User impact<br>Degraded performance. Often SEV2 if user-facing and sustained, otherwise SEV3.<br><br>## What to check (triage)<br>### Grafana<br>- Golden Signals:<br>  - Latency p95 crosses 0.25s<br>  - Saturation (CPU/memory) may rise<br><br>### Prometheus query<br>```promql<br>histogram_quantile(0.95, sum by (le) (rate(http_request_latency_seconds_bucket[5m])))<br>````<br><br>### Logs (OpenSearch Discover)<br><br>* `latency_ms &gt;= 500`<br>* Focus on high-latency paths:<br><br>  * `path: &quot;/work&quot;`<br><br>## Likely causes<br><br>* Heavy request path (in this project: /work latency injection).<br>* Resource saturation (CPU throttling, memory pressure).<br>* Thread/worker contention.<br><br>## Mitigation steps<br><br>1. Identify whether latency is tied to a specific path:<br><br>* In logs, filter by `path: &quot;/work&quot;` and high `latency_ms`.<br><br>2. Reduce load or stop the latency generator (during simulation).<br><br>3. Restart app if it is stuck:<br><br>```bash<br>docker restart sre_app<br>```<br><br>4. Consider adjusting capacity (future improvement):<br><br>* Increase gunicorn workers/threads (not changing in this project).<br>* Move latency-heavy endpoints away from the hot path.<br><br>## Rollback steps<br><br>* Revert last change and redeploy:<br><br>```bash<br>cd ~/sre-mini-prod-aws<br>git log --oneline -n 10<br># git checkout &lt;known_good_commit&gt;<br>cd observability<br>docker compose up -d --build<br>```<br><br>## Verify recovery<br><br>* p95 latency falls below 0.25s.<br>* Alert resolves.<br>* Logs show reduced `latency_ms` outliers.</pre><p>Path: runbooks/ALERT-disk-full.md</p><pre># Runbook: DiskFillingUpRoot (severity=warning)<br><br>## What it means<br>Root filesystem usage is above 85% for 5 minutes. Disk pressure can cause crashes and data loss.<br><br>## User impact<br>Often indirect at first: slower writes, failures, container instability. Can escalate quickly.<br><br>## What to check<br>### Grafana Host dashboard<br>- Disk root filesystem percent used (panel)<br><br>### Prometheus query<br>```promql<br>100 * (1 - (node_filesystem_avail_bytes{mountpoint=&quot;/&quot;} / node_filesystem_size_bytes{mountpoint=&quot;/&quot;}))<br>````<br><br>### VM checks<br><br>```bash<br>df -h<br>sudo du -xh /var | sort -h | tail -n 20<br>docker system df<br>```<br><br>## Likely causes<br><br>* Log growth (app logs, container logs).<br>* OpenSearch data volume growth.<br>* Docker images and unused layers.<br><br>## Mitigation steps<br><br>1. Check and reduce Docker storage:<br><br>```bash<br>docker system prune -af<br>```<br><br>2. If logs are the driver, rotate or truncate:<br><br>```bash<br>sudo truncate -s 0 /var/lib/docker/containers/*/*-json.log || true<br>```<br><br>3. If OpenSearch data is too large, delete old indices (project is single index, be careful).<br><br>## Rollback steps<br><br>* Not usually code rollback. This is capacity/ops remediation.<br><br>## Verify recovery<br><br>* Disk usage drops below threshold.<br>* Alert resolves.<br>* Services stay stable.</pre><h4>10.3 Postmortem template</h4><p>Create postmortems/template.md:</p><pre># Postmortem: &lt;Incident Title&gt;<br><br>## Summary<br>- What happened, in 2–4 sentences.<br><br>## Customer impact<br>- Who was affected?<br>- What was the impact (errors, latency, downtime)?<br>- Duration and scope.<br><br>## Timeline (UTC)<br>- &lt;YYYY-MM-DD HH:MM&gt; Detection<br>- &lt;YYYY-MM-DD HH:MM&gt; Triage<br>- &lt;YYYY-MM-DD HH:MM&gt; Mitigation<br>- &lt;YYYY-MM-DD HH:MM&gt; Recovery confirmed<br>- &lt;YYYY-MM-DD HH:MM&gt; Incident resolved<br><br>## Root cause<br>- The direct technical cause.<br><br>## Contributing factors<br>- Conditions that made the incident worse or more likely.<br><br>## Detection and response<br>- How we detected it (alert/dashboard/logs).<br>- What we did to respond, including time to mitigate.<br><br>## What went well<br>- Concrete items.<br><br>## What went wrong<br>- Concrete items.<br><br>## Action items<br>| Action | Owner | Priority | Due date |<br>|---|---|---|---|<br>|  |  |  |  |<br><br>## Prevent recurrence<br>- Monitoring improvements<br>- Code changes<br>- Capacity improvements<br>- Process changes</pre><h3>Step 11: Incident simulation (2 incidents with evidence)</h3><p>Incident simulations show you can operate the system, not just deploy it. You will run:</p><ul><li>Normal load</li><li>A 5xx spike incident</li><li>A latency spike incident</li></ul><h4>11.1 Scripts</h4><p>Path: scripts/load_normal.sh</p><pre>#!/bin/bash<br>set -e<br>URL=&quot;${1:-http://localhost}&quot;<br>for i in $(seq 1 200); do<br>  curl -s &quot;$URL/&quot; &gt;/dev/null<br>  curl -s &quot;$URL/healthz&quot; &gt;/dev/null<br>  sleep 0.05<br>done<br>echo &quot;normal load done&quot;</pre><p>Path: scripts/generate_5xx.sh</p><pre>#!/bin/bash<br>set -e<br>URL=&quot;${1:-http://localhost}&quot;<br>for i in $(seq 1 300); do<br>  curl -s -o /dev/null -w &quot;%{http_code}\n&quot; &quot;$URL/error&quot; | tail -n 1 &gt;/dev/null<br>  sleep 0.05<br>done<br>echo &quot;5xx spike done&quot;</pre><p>Path: scripts/generate_latency.sh</p><pre>#!/bin/bash<br>set -e<br>URL=&quot;${1:-http://localhost}&quot;<br>for i in $(seq 1 120); do<br>  curl -s &quot;$URL/work?ms=1200&quot; &gt;/dev/null<br>  sleep 0.05<br>done<br>echo &quot;latency spike done&quot;</pre><p><strong>On the VM:</strong></p><pre># After copying the files to VM<br>chmod +x scripts/*.sh<br>bash scripts/load_normal.sh http://localhost</pre><h4>11.2 Simulate Incident 1: 5xx spike</h4><p>Run: bash scripts/generate_5xx.sh <a href="http://localhost/">http://localhost</a></p><p>Expected evidence:</p><ul><li>Grafana Golden Signals: Errors and error ratio spike</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PR6BXp8Vc08HS47iRY8mw.png" /><figcaption>Fig: Grafana Golden Signals</figcaption></figure><ul><li>Prometheus: High5xxErrorRatio fires (critical)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcpRm2dzpKFrhd5FhER7SA.png" /><figcaption>Fig: Prometheus</figcaption></figure><ul><li>Alertmanager receiver logs show webhook payload: docker logs -f alert_receiver</li><li>OpenSearch Discover: intentional_error_triggered log events appear during the incident window</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yQVf1qP5jguya2v1AHuiQ.png" /><figcaption>Fig: OpenSearch Discover</figcaption></figure><h4>11.3 Simulate Incident 2: latency spike</h4><p>Run: bash scripts/generate_latency.sh <a href="http://localhost/">http://localhost</a></p><p>Expected evidence:</p><ul><li>Grafana Golden Signals: p95 latency crosses 250ms</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69E1ETTD35KXcMgIaSIlzQ.png" /><figcaption>Fig: Grafana Golden Signals</figcaption></figure><ul><li>Prometheus: HighLatencyP95 fires (warning)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OraG36rSLvr5603SGPlGw.png" /><figcaption>Fig: Prometheus</figcaption></figure><ul><li>OpenSearch Discover: latency_ms &gt;= 500 shows spikes in the incident window</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZ0st4T_p3g-uVtvCpfgFw.png" /><figcaption>Fig: OpenSearch Discover</figcaption></figure><h3>Step 12: Write 2 sample postmortems (based on your simulations)</h3><p>These are your “real SRE artifacts.” Write them as if they happened in production, even though you triggered them intentionally.</p><h4>12.1 postmortems/PM-incident-5xx-spike.md</h4><pre># Postmortem: 5xx Spike due to Unprotected Error Endpoint<br><br>## Summary<br>A sustained spike of HTTP 500 responses occurred when the `/error` endpoint was hit repeatedly. The error ratio exceeded 5% for more than 2 minutes, triggering a critical alert. The issue resolved after the error traffic stopped and service health returned to normal.<br><br>## Customer impact<br>- Users experienced elevated error rates for requests routed to the service.<br>- Impact type: partial outage (high failure rate).<br>- Duration: ~3–6 minutes during active traffic generation.<br>- Scope: affected all users hitting the service during the window.<br><br>## Timeline (UTC)<br>- 2025-12-27 03:05 Detection: `High5xxErrorRatio` alert fired (critical).<br>- 2025-12-27 03:06 Triage: Grafana error ratio panel confirmed spike; Prometheus showed 5xx rate increase.<br>- 2025-12-27 03:07 Investigation: OpenSearch logs showed repeated `intentional_error_triggered`.<br>- 2025-12-27 03:08 Mitigation: Stopped the 5xx generation traffic.<br>- 2025-12-27 03:09 Recovery confirmed: error ratio returned to baseline; alert resolved.<br>- 2025-12-27 03:10 Incident resolved.<br><br>## Root cause<br>The service includes an endpoint (`/error`) that always returns HTTP 500 and is not protected by auth or rate limiting. Repeated calls drove the 5xx ratio above the alert threshold.<br><br>## Contributing factors<br>- No access control on debug/test endpoints.<br>- No rate limiting or request filtering.<br>- Alert focused on symptoms (good), but dashboards lacked “top failing paths” breakdown.<br><br>## Detection and response<br>- Detection: Prometheus alert `High5xxErrorRatio` (critical) based on 5xx ratio.<br>- Investigation:<br>  - Grafana Golden Signals confirmed error ratio spike.<br>  - OpenSearch logs confirmed repeated error trigger events.<br>- Response time: mitigation within ~3 minutes of detection (simulated).<br><br>## What went well<br>- Alert severity routing worked, critical alert reached the receiver.<br>- Logs and metrics correlated cleanly by time window.<br>- Runbook steps were straightforward and executable.<br><br>## What went wrong<br>- Debug endpoint design is unsafe for any environment exposed to the Internet.<br>- No automated protection against abusive traffic patterns.<br><br>## Action items<br>| Action | Owner | Priority | Due date |<br>|---|---|---|---|<br>| Add auth or remove debug endpoints like `/error` in non-dev deployments | Owner | P0 | 2026-01-10 |<br>| Add rate limiting concept (future extension) | Owner | P1 | 2026-01-20 |<br>| Add dashboard panel: “Top paths by 5xx” | Owner | P1 | 2026-01-12 |<br>| Add alert annotation linking to runbook path | Owner | P2 | 2026-01-15 |<br><br>## Prevent recurrence<br>- Code: remove or protect failure-injection endpoints.<br>- Monitoring: add breakdown panels for error sources.<br>- Process: require “production exposure review” for endpoints.</pre><h4>12.2 postmortems/PM-incident-latency-spike.md</h4><pre># Postmortem: p95 Latency Spike due to Latency Injection Load<br><br>## Summary<br>p95 latency exceeded 250ms for more than 3 minutes due to repeated requests to `/work?ms=1200`, which intentionally sleeps to simulate slow work. The warning alert fired as expected and resolved once the latency traffic stopped.<br><br>## Customer impact<br>- Users experienced degraded performance (slow responses).<br>- Impact type: performance degradation.<br>- Duration: ~3–6 minutes during active traffic generation.<br>- Scope: requests served during the window; higher impact for endpoints competing for the same worker capacity.<br><br>## Timeline (UTC)<br>- 2025-12-27 03:20 Detection: `HighLatencyP95` alert fired (warning).<br>- 2025-12-27 03:21 Triage: Grafana Golden Signals showed p95 above 0.25s; CPU/memory checked for saturation.<br>- 2025-12-27 03:22 Investigation: OpenSearch logs showed many `/work` requests with high `latency_ms`.<br>- 2025-12-27 03:23 Mitigation: Stopped latency generation traffic.<br>- 2025-12-27 03:24 Recovery confirmed: p95 fell below threshold; alert resolved.<br>- 2025-12-27 03:25 Incident resolved.<br><br>## Root cause<br>The `/work` endpoint intentionally injects latency. Repeated calls increased observed p95 latency beyond the 250ms SLO threshold.<br><br>## Contributing factors<br>- Strict latency SLO (intentional for demonstrability).<br>- Single-host, shared-resource environment, so heavy work affects all request handling.<br>- No separation of “slow work” from primary request path.<br><br>## Detection and response<br>- Detection: Prometheus alert `HighLatencyP95` (warning) based on histogram p95 query.<br>- Investigation:<br>  - Grafana confirmed symptom.<br>  - OpenSearch verified high `latency_ms` outliers and concentrated traffic to `/work`.<br><br>## What went well<br>- Warning severity correctly routed and visible in receiver logs.<br>- Histogram-based latency instrumentation worked as expected.<br>- Evidence was consistent across dashboards and logs.<br><br>## What went wrong<br>- The environment has no autoscaling or worker tuning beyond defaults.<br>- No explicit SLI for “percent of requests under threshold,” only p95.<br><br>## Action items<br>| Action | Owner | Priority | Due date |<br>|---|---|---|---|<br>| Tune gunicorn workers/threads based on instance size (future extension) | Owner | P1 | 2026-01-20 |<br>| Add latency SLI: percentage of requests under 250ms (future extension) | Owner | P2 | 2026-01-25 |<br>| Add note in docs about autoscaling patterns (future extension) | Owner | P2 | 2026-01-25 |<br><br>## Prevent recurrence<br>- Capacity: tune worker model and consider splitting workloads.<br>- Monitoring: track both p95 and “% under threshold.”<br>- Architecture: separate slow work path from user-facing request path.</pre><h3>Step 13: Verification checklist</h3><p>A complete system checklist:</p><h4>1) Terraform</h4><ul><li>terraform apply succeeds</li><li>Security group: SSH only from your IP</li><li>App port 80 is public</li><li>Grafana/Prometheus/Dashboards restricted to your IP</li></ul><h4>2) Service</h4><ul><li>GET /healthz returns 200</li><li>GET /metrics shows counters and histogram buckets</li><li>GET /error returns 500</li><li>GET /work?ms=1000 returns 200 with visible latency</li></ul><h4>3) Monitoring</h4><ul><li>Prometheus shows targets UP for app and node</li><li>Grafana can query Prometheus</li><li>Dashboards show live traffic, errors, p95, CPU, memory, disk</li></ul><h4>4) Alerting</h4><ul><li>Test service down alert by stopping app container:</li></ul><pre>docker stop sre_app</pre><ul><li>5xx alert fires after running 5xx script</li><li>latency alert fires after running latency script</li><li>alert receiver shows webhook payloads</li><li>restart app:</li></ul><pre>docker start sre_app</pre><h4>5) Logging</h4><ul><li>OpenSearch Dashboards Discover shows app logs</li><li>5xx logs appear when /error is called</li><li>latency logs appear for /work</li></ul><h4>6) Incident package</h4><ul><li>runbooks exist for each alert</li><li>postmortems exist with timeline and action items</li><li>demo script exists</li></ul><h3>Step 14: Clean up (important)</h3><p>To avoid ongoing AWS costs, destroy infrastructure when done:</p><pre>cd terraform<br>terraform destroy -var=&quot;key_name=sre-mini-key&quot; -var=&quot;my_ip_cidr=$(curl -s https://checkip.amazonaws.com)/32&quot;</pre><h3>Conclusion</h3><p>This project built a complete, production-style observability and incident-response setup on AWS. Using Terraform, we provisioned an EC2 VM and ran a Flask service with /healthz and /metrics, plus controlled failure and latency injection. Prometheus scraped metrics and evaluated alert rules, Alertmanager routed alerts by severity, and Grafana visualized Golden Signals and host health. For logs, Fluent Bit shipped structured JSON logs to OpenSearch for centralized search and troubleshooting. We also added SEV definitions, runbooks, and a postmortem template, and validated everything through two incident simulations (5xx spike and latency spike) with evidence across dashboards, alerts, and logs, along with two postmortems.</p><p>Along the way, we learned how to build systems that are truly operable. We practiced defining SLIs/SLOs and error budgets, validating alert pipelines end-to-end, and investigating incidents using metrics and logs together. Most importantly, we learned how to turn incidents into clear fixes and long-term reliability improvements.</p><p>Next, we can extend this stack with Nginx (reverse proxy + rate limiting), TLS, a split app and observability topology, multi-window burn-rate alerting, CI checks for configs and dashboards, and k6 load testing to stress the system. This foundation is a solid base for building bigger and more resilient services.</p><p>Happy New Year 2026 🎉🚀</p><h3>Further learning resources</h3><ul><li>Google SRE Book (Monitoring, SLOs, Incident Response)</li><li>Prometheus documentation (instrumentation, histograms, alerting rules)</li><li>Grafana documentation (dashboards, Prometheus datasource)</li><li>Alertmanager documentation (routing, receivers)</li><li>Terraform AWS Provider docs (EC2, security groups)</li><li>Fluent Bit and OpenSearch docs (tail input, OpenSearch output, index patterns)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dCMqFMY3_kpQ0QCqsUXdPg.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f9d92a9326" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyond-localhost/sre-mini-production-stack-on-aws-f1f9d92a9326">SRE Production Stack on AWS</a> was originally published in <a href="https://medium.com/beyond-localhost">Beyond Localhost</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read-Replica using PostgreSQL]]></title>
            <link>https://medium.com/@thisis-Shitanshu/read-replica-using-postgresql-a4a70a0e96a3?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4a70a0e96a3</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 11:09:38 GMT</pubDate>
            <atom:updated>2025-10-22T11:25:06.717Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Hands-On Guide to Spinning Up an Analytics Environment on PostgreSQL</h4><p>Most analytics projects stall on day one because access to production data is risky, slow, or blocked. The goal of this guide is to help you, an active Data Engineer, give your Data Science and Analytics partners a safe and fast runway. We’ll start with the basics, define a hypothetical business requirement, create a realistic local “production” database, stand up a read-replica using PostgreSQL’s logical replication, and then build a minimal but professional analytics workflow with code you can run today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*ZV1Lvh5PCsRQSkJa2ShlLQ.png" /></figure><h3>The business story we’re solving</h3><p>Imagine <strong>ShopNimble</strong>, a mid-size e-commerce company. The product team runs a monolith with PostgreSQL as the primary transactional database. The analytics stakeholders want to answer three questions in the next week:</p><ol><li>What’s our 7/30/90-day revenue, and how does it trend?</li><li>Which top 10 products drive revenue by day?</li><li>What is the repeat purchase rate for customers who bought in the last 60 days?</li></ol><p>They need fresh data (hourly to daily), reproducible numbers, and confidence that the analysis won’t slow down the checkout experience. Direct queries on production are off-limits. We will set up a <strong>read-replica</strong> and build a small but solid analytics layer on top.</p><blockquote><strong>Key idea:</strong> We never touch production for analytics. We read from a replica, keep secrets out of Git, ship a quick first result, and iterate.</blockquote><h3>What we’ll build locally</h3><p>We’ll run two PostgreSQL containers:</p><ul><li>pg_prod: our production database (primary).</li><li>pg_replica: our analytics read-replica (subscriber) kept in sync via logical replication.</li></ul><p>We’ll load a small fake schema and seed data, publish changes from pg_prod, and subscribe from pg_replica. We’ll connect a simple Python notebook/script to the replica, explore data, run a first cut of metrics, add lightweight data quality checks, and sketch a path to a scheduled daily extract.</p><h3>Step 1: Spin up Postgres primary and replica</h3><p>Create a project folder and add three files: docker-compose.yml, init_prod.sql, and .env.</p><ul><li>docker-compose.yml</li></ul><pre>services:<br>  pg_prod:<br>    image: postgres:15<br>    container_name: pg_prod<br>    environment:<br>      POSTGRES_USER: appuser<br>      POSTGRES_PASSWORD: appsecret<br>      POSTGRES_DB: appdb<br>    ports:<br>      - &quot;5433:5432&quot;   # expose prod on localhost:5433 (so it won&#39;t clash)<br>    command: [<br>      &quot;postgres&quot;,<br>      &quot;-c&quot;, &quot;wal_level=logical&quot;,<br>      &quot;-c&quot;, &quot;max_wal_senders=10&quot;,<br>      &quot;-c&quot;, &quot;max_replication_slots=10&quot;,<br>      &quot;-c&quot;, &quot;shared_buffers=256MB&quot;<br>    ]<br>    volumes:<br>      - ./init_prod.sql:/docker-entrypoint-initdb.d/init_prod.sql<br><br>  pg_replica:<br>    image: postgres:15<br>    container_name: pg_replica<br>    environment:<br>      POSTGRES_USER: analyst<br>      POSTGRES_PASSWORD: analystsecret<br>      POSTGRES_DB: analyticsdb<br>    ports:<br>      - &quot;5434:5432&quot;   # expose replica on localhost:5434<br>    command: [<br>      &quot;postgres&quot;,<br>      &quot;-c&quot;, &quot;wal_level=logical&quot;,<br>      &quot;-c&quot;, &quot;max_wal_senders=10&quot;,<br>      &quot;-c&quot;, &quot;max_replication_slots=10&quot;,<br>      &quot;-c&quot;, &quot;shared_buffers=256MB&quot;<br>    ]</pre><ul><li>init_prod.sql (schema + seed data on “prod”)</li></ul><pre>-- Core entities<br>CREATE TABLE public.users (<br>  id            BIGSERIAL PRIMARY KEY,<br>  email         TEXT UNIQUE NOT NULL,<br>  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>CREATE TABLE public.products (<br>  id            BIGSERIAL PRIMARY KEY,<br>  sku           TEXT UNIQUE NOT NULL,<br>  name          TEXT NOT NULL,<br>  price_cents   INT NOT NULL CHECK (price_cents &gt;= 0),<br>  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>CREATE TABLE public.orders (<br>  id            BIGSERIAL PRIMARY KEY,<br>  user_id       BIGINT NOT NULL REFERENCES public.users(id),<br>  status        TEXT NOT NULL CHECK (status IN (&#39;paid&#39;,&#39;pending&#39;,&#39;failed&#39;)),<br>  total_cents   INT NOT NULL CHECK (total_cents &gt;= 0),<br>  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()<br>);<br><br>CREATE TABLE public.order_items (<br>  id            BIGSERIAL PRIMARY KEY,<br>  order_id      BIGINT NOT NULL REFERENCES public.orders(id),<br>  product_id    BIGINT NOT NULL REFERENCES public.products(id),<br>  quantity      INT NOT NULL CHECK (quantity &gt; 0),<br>  price_cents   INT NOT NULL CHECK (price_cents &gt;= 0)<br>);<br><br>-- Minimal seed data<br>INSERT INTO public.users (email, created_at) VALUES<br>(&#39;a@x.com&#39;, now() - interval &#39;80 days&#39;),<br>(&#39;b@x.com&#39;, now() - interval &#39;40 days&#39;),<br>(&#39;c@x.com&#39;, now() - interval &#39;10 days&#39;);<br><br>INSERT INTO public.products (sku, name, price_cents) VALUES<br>(&#39;SKU-1&#39;, &#39;Coffee Grinder&#39;, 4999),<br>(&#39;SKU-2&#39;, &#39;Kettle Pro&#39;, 6999),<br>(&#39;SKU-3&#39;, &#39;Espresso Beans&#39;, 1599);<br><br>-- Some orders across time windows<br>INSERT INTO public.orders (user_id, status, total_cents, created_at) VALUES<br>(1, &#39;paid&#39;, 4999, now() - interval &#39;75 days&#39;),<br>(1, &#39;paid&#39;, 8598, now() - interval &#39;38 days&#39;),<br>(2, &#39;paid&#39;, 1599, now() - interval &#39;33 days&#39;),<br>(2, &#39;failed&#39;, 6999, now() - interval &#39;20 days&#39;),<br>(3, &#39;paid&#39;, 8598, now() - interval &#39;8 days&#39;),<br>(3, &#39;paid&#39;, 1599, now() - interval &#39;2 days&#39;);<br><br>-- Items reflecting those orders<br>INSERT INTO public.order_items (order_id, product_id, quantity, price_cents) VALUES<br>(1, 1, 1, 4999),<br>(2, 2, 1, 6999),<br>(2, 3, 1, 1599),<br>(3, 3, 1, 1599),<br>(4, 2, 1, 6999),<br>(5, 2, 1, 6999),<br>(5, 3, 1, 1599),<br>(6, 3, 1, 1599);</pre><ul><li>.env (local only; do not commit)</li></ul><pre>PG_REPL_USER=replicator<br>PG_REPL_PASS=replsecret</pre><p>Start the containers:</p><pre>docker compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYJLlI1pBWQuUNwwUQIv6w.png" /><figcaption>Fig: Starting both docker container</figcaption></figure><h3>Step 2: Create a publication (prod) and a subscription (replica)</h3><p>We’ll use PostgreSQL’s logical replication. On pg_prod, we publish the tables we want to replicate. On pg_replica, we create a subscription pointing to pg_prod.</p><blockquote><strong>Note:</strong> Logical replication in PostgreSQL is a method of copying specific data and its changes from one database (the publisher) to another (the subscriber) based on logical identifiers like primary keys, rather than physical files. It uses a publish–subscribe model where the publisher defines which tables and changes to share, and the subscriber pulls and applies those changes in the same order to stay consistent. When replication starts, PostgreSQL takes an initial snapshot of the data and sends it to the subscriber, after which only new changes (inserts, updates, deletes) are continuously replicated. This allows flexible setups such as replicating only certain tables, syncing between different PostgreSQL versions or platforms, or combining data from multiple databases. Logical replication is often used for incremental updates, analytics, migrations, or data sharing, and the subscriber can also act as a publisher for others. It works best when the subscriber is treated as read-only to avoid data conflicts. (Source: <a href="https://www.postgresql.org/docs/current/logical-replication.html">PostgreSQL Logical Replication Docs</a>)</blockquote><h4>2.1 Create a replication user and publication on pg_prod</h4><pre># in a new terminal<br>docker exec -it pg_prod psql -U appuser -d appdb</pre><pre>-- Create a dedicated replication user (password from your .env in real life)<br>CREATE ROLE replicator WITH LOGIN REPLICATION PASSWORD &#39;replsecret&#39;;<br><br>-- Allow this user to read our schemas<br>GRANT USAGE ON SCHEMA public TO replicator;<br>GRANT SELECT ON ALL TABLES IN SCHEMA public TO replicator;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO replicator;<br><br>-- Create a publication for the tables we want in analytics<br>CREATE PUBLICATION pub_appdb FOR TABLE<br>  public.users,<br>  public.products,<br>  public.orders,<br>  public.order_items;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOR80enCSwEy-fVf7nFa-Q.png" /></figure><h4>2.2 Create a subscription on pg_replica</h4><p>Find the pg_prod hostname the replica can reach. Within Docker, services can reach each other via service names. From pg_replica, the primary is accessible as pg_prod on port 5432.</p><pre>docker exec -it pg_replica psql -U analyst -d analyticsdb</pre><pre>-- Create matching empty tables first (logical replication expects compatible schemas)<br>CREATE TABLE public.users (<br>  id BIGINT PRIMARY KEY, email TEXT UNIQUE NOT NULL, created_at TIMESTAMPTZ NOT NULL<br>);<br>CREATE TABLE public.products (<br>  id BIGINT PRIMARY KEY, sku TEXT UNIQUE NOT NULL, name TEXT NOT NULL,<br>  price_cents INT NOT NULL, created_at TIMESTAMPTZ NOT NULL<br>);<br>CREATE TABLE public.orders (<br>  id BIGINT PRIMARY KEY, user_id BIGINT NOT NULL, status TEXT NOT NULL,<br>  total_cents INT NOT NULL, created_at TIMESTAMPTZ NOT NULL<br>);<br>CREATE TABLE public.order_items (<br>  id BIGINT PRIMARY KEY, order_id BIGINT NOT NULL, product_id BIGINT NOT NULL,<br>  quantity INT NOT NULL, price_cents INT NOT NULL<br>);<br><br>-- Create the subscription to pull changes from the primary<br>CREATE SUBSCRIPTION sub_appdb<br>CONNECTION &#39;host=pg_prod port=5432 dbname=appdb user=replicator password=replsecret&#39;<br>PUBLICATION pub_appdb<br>WITH (create_slot = true, copy_data = true);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTI6UrcvtBml7kREroZX5A.png" /></figure><p>After a few seconds, the seed data should appear on the replica. Verify quickly:</p><pre>SELECT count(*) FROM public.orders;         -- expect 6<br>SELECT count(*) FROM public.order_items;    -- expect 8</pre><p>You now have a local prod-like primary and a separate replica suitable for analytics reads.</p><h4><strong>Important points</strong></h4><ul><li>Logical replication gives you a clean, decoupled analytics endpoint.</li><li>The replica can be queried freely without disturbing production.</li><li>You still create a <strong>read-only</strong> analytics user for day-to-day work.</li></ul><h3>Step 3: Create a safe, minimal analytics workspace</h3><p>We’ll keep code in Git and secrets out of Git. Create a Python virtual environment and a small utility to read from the replica.</p><pre>python -m venv .venv<br>source .venv/bin/activate<br>pip install SQLAlchemy psycopg2-binary pandas python-decouple matplotlib &quot;great_expectations&gt;=0.18.12,&lt;1.0&quot; </pre><p>Create a .gitignore:</p><pre>.venv/<br>.env<br>__pycache__/<br>.ipynb_checkpoints/</pre><p>Create a local .env (do not commit):</p><pre>PG_HOST=localhost<br>PG_PORT=5434<br>PG_DB=analyticsdb # Replica DB<br>PG_USER=analyst<br>PG_PASSWORD=analystsecret</pre><p>Create analytics.py:</p><pre># analytics.py<br>import pandas as pd<br>from decouple import config<br>from sqlalchemy import create_engine<br>from sqlalchemy.engine import Engine<br>from urllib.parse import quote_plus<br><br>PG_HOST = config(&quot;PG_HOST&quot;)<br>PG_PORT = config(&quot;PG_PORT&quot;, cast=int, default=5434)<br>PG_DB   = config(&quot;PG_DB&quot;)<br>PG_USER = config(&quot;PG_USER&quot;)<br>PG_PASS = config(&quot;PG_PASSWORD&quot;)<br><br>def make_engine() -&gt; Engine:<br>    # URL-escape the password in case it has special chars<br>    url = f&quot;postgresql+psycopg2://{PG_USER}:{quote_plus(PG_PASS)}@{PG_HOST}:{PG_PORT}/{PG_DB}&quot;<br>    return create_engine(url, pool_pre_ping=True, future=True)<br><br>ENGINE = make_engine()<br><br>def read_df(sql: str, params=None) -&gt; pd.DataFrame:<br>    # use SQLAlchemy connection for pandas 2.x<br>    with ENGINE.connect() as conn:<br>        return pd.read_sql(sql, conn, params=params)<br><br>if __name__ == &quot;__main__&quot;:<br>    df = read_df(&quot;SELECT * FROM public.orders ORDER BY created_at DESC LIMIT 5;&quot;)<br>    print(df.head())</pre><p>Run it:</p><pre>python analytics.py</pre><p>You should see recent orders fetched from the replica.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*lUtGMJxo53KDQi4yYx4Gug.png" /><figcaption>Fig: Recent orders fetched from the replica.</figcaption></figure><h3>Step 4: Explore visually, verify assumptions, and document</h3><p>Open DBeaver or DataGrip and connect to localhost:5434 with analyst/analystsecret. Look at table sizes, recent dates, and NULL patterns. Write down any questions or oddities in a shared doc (even a simple README). In a real team, this becomes your living “data notes” that drastically reduces back-and-forth.</p><h4>What you want to learn right away:</h4><ul><li>Which dates are populated, and how fresh they are.</li><li>Which status values are valid in orders.status.</li><li>Whether order_items.price_cents always matches products.price_cents.</li><li>Whether orders.total_cents equals the sum of its items.</li></ul><h3>Step 5: Deliver a fast first cut of stakeholder metrics</h3><p>Create metrics.py to compute the requested KPIs from the replica.</p><pre>import pandas as pd<br>from decouple import config<br>import psycopg2<br><br>from analytics import read_df<br><br>def revenue_since(days: int) -&gt; pd.DataFrame:<br>    sql = f&quot;&quot;&quot;<br>    SELECT date_trunc(&#39;day&#39;, created_at) AS day,<br>           SUM(total_cents)/100.0 AS revenue_usd<br>    FROM public.orders<br>    WHERE status = &#39;paid&#39; AND created_at &gt;= now() - interval &#39;{days} days&#39;<br>    GROUP BY 1<br>    ORDER BY 1;<br>    &quot;&quot;&quot;<br>    return read_df(sql)<br><br>def top_products(days: int) -&gt; pd.DataFrame:<br>    sql = f&quot;&quot;&quot;<br>    SELECT p.sku, p.name,<br>           SUM(oi.quantity * oi.price_cents)/100.0 AS revenue_usd<br>    FROM public.order_items oi<br>    JOIN public.orders o   ON o.id = oi.order_id<br>    JOIN public.products p ON p.id = oi.product_id<br>    WHERE o.status=&#39;paid&#39; AND o.created_at &gt;= now() - interval &#39;{days} days&#39;<br>    GROUP BY 1,2<br>    ORDER BY 3 DESC<br>    LIMIT 10;<br>    &quot;&quot;&quot;<br>    return read_df(sql)<br><br>def repeat_purchase_rate(days: int) -&gt; pd.DataFrame:<br>    sql = f&quot;&quot;&quot;<br>    WITH buyers AS (<br>      SELECT user_id, min(created_at) AS first_buy<br>      FROM public.orders<br>      WHERE status=&#39;paid&#39;<br>      GROUP BY 1<br>    ),<br>    recent AS (<br>      SELECT user_id<br>      FROM public.orders<br>      WHERE status=&#39;paid&#39; AND created_at &gt;= now() - interval &#39;{days} days&#39;<br>      GROUP BY 1<br>    ),<br>    recency AS (<br>      SELECT r.user_id,<br>             COUNT(o.id) AS paid_orders_last_{days}<br>      FROM recent r<br>      JOIN public.orders o ON o.user_id = r.user_id AND o.status=&#39;paid&#39;<br>                           AND o.created_at &gt;= now() - interval &#39;{days} days&#39;<br>      GROUP BY 1<br>    )<br>    SELECT<br>      (SELECT COUNT(*) FROM recency) AS buyers_last_{days},<br>      (SELECT COUNT(*) FROM recency WHERE paid_orders_last_{days} &gt;= 2) AS repeat_buyers,<br>      (SELECT CASE WHEN COUNT(*)=0 THEN 0<br>              ELSE ROUND(100.0 * SUM(CASE WHEN paid_orders_last_{days} &gt;= 2 THEN 1 ELSE 0 END)<br>                   / COUNT(*), 2) END<br>       FROM recency) AS repeat_rate_pct;<br>    &quot;&quot;&quot;<br>    return read_df(sql)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;&gt;&gt;&gt; Revenue 7d: &lt;&lt;&lt;&quot;)<br>    print(revenue_since(7).tail())<br>    print(&quot;\n&gt;&gt;&gt; Top products 30d: &lt;&lt;&lt;&quot;)<br>    print(top_products(30))<br>    print(&quot;\n&gt;&gt;&gt; Repeat purchase rate 60d: &lt;&lt;&lt;&quot;)<br>    print(repeat_purchase_rate(60))</pre><p>Run it and share the first tables with the stakeholders. This is your quick, useful checkpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*sc-SZsp_w9AbeLJcANZNHA.png" /><figcaption>Fig: `$ python3 metrics.py`</figcaption></figure><h3>Step 6: Add lightweight data quality checks</h3><p>We’ll write a couple of simple rules to avoid obvious mistakes. Start small and grow only if needed.</p><ul><li>dq_checks.py</li></ul><pre># dq_checks.py<br>import sys<br>import great_expectations as gx<br>from analytics import read_df<br><br>def dq_orders_basic() -&gt; None:<br>    df = read_df(&quot;SELECT id, total_cents, status, created_at FROM public.orders;&quot;)<br>    ge_df = gx.from_pandas(df)<br>    ge_df.expect_column_values_to_not_be_null(&quot;id&quot;)<br>    ge_df.expect_column_values_to_not_be_null(&quot;created_at&quot;)<br>    ge_df.expect_column_values_to_be_between(&quot;total_cents&quot;, min_value=0)<br>    ge_df.expect_column_values_to_match_regex(&quot;status&quot;, r&quot;^(paid|pending|failed)$&quot;)<br><br>    result = ge_df.validate()<br>    if not result[&quot;success&quot;]:<br>        print(&quot;❌ Data quality failed for &#39;orders&#39;&quot;)<br>        for r in result[&quot;results&quot;]:<br>            if not r[&quot;success&quot;]:<br>                print(&quot; -&quot;, r[&quot;expectation_config&quot;][&quot;expectation_type&quot;])<br>        sys.exit(1)<br>    print(&quot;✅ Data quality passed for &#39;orders&#39;&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Running DQ checks...&quot;)<br>    dq_orders_basic()</pre><p>This won’t replace enterprise data contracts, but it catches basic issues early and cheaply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*fTYVvuvntWzAgt2656Q4QQ.png" /><figcaption>Fig: Successful DQ checks</figcaption></figure><h3>Step 7: Sketch a daily job (light scheduling)</h3><p>You don’t need a full scheduler on day one. A simple script or a cron entry can export a daily snapshot to a CSV or parquet in an object store. Here is a tiny Python example; replace the “save to local” with an S3/GCS upload when you’re ready.</p><ul><li>snapshot_daily.py</li></ul><pre># snapshot_daily.py<br>import pandas as pd<br>from datetime import datetime, timezone, timedelta<br>from analytics import read_df<br><br>def run():<br>    since = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()<br>    df = read_df(f&quot;&quot;&quot;<br>        SELECT o.*, u.email<br>        FROM public.orders o<br>        JOIN public.users u ON u.id = o.user_id<br>        WHERE o.created_at &gt;= &#39;{since}&#39;<br>    &quot;&quot;&quot;)<br>    out = f&quot;./snapshots/orders_{datetime.utcnow().date()}.csv&quot;<br>    df.to_csv(out, index=False)<br>    print(&quot;Wrote&quot;, out)<br><br>if __name__ == &quot;__main__&quot;:<br>    run()</pre><h4>Insert a fresh order &amp; item on the primary</h4><pre># open psql on the primary<br>docker exec -it pg_prod psql -U appuser -d appdb</pre><p>Create a new paid order “now” and one item:</p><pre>-- make a new order<br>INSERT INTO public.orders (user_id, status, total_cents, created_at)<br>VALUES (1, &#39;paid&#39;, 1599, now())<br>RETURNING id;<br><br>-- note the returned id, say it&#39;s 7 (check it with SELECT ...)<br>-- add a line item for product 3 (Espresso Beans)<br>INSERT INTO public.order_items (order_id, product_id, quantity, price_cents)<br>VALUES (7, 3, 1, 1599);</pre><p>You should see the new row in your snapshot. Now run:</p><pre>python snapshot_daily.py</pre><p>Open snapshots/orders_&lt;today&gt;.csv — you’ll have rows.</p><blockquote>Later, you can move repeatable transforms to <strong>dbt</strong> and trigger with <strong>Airflow</strong>. For many teams, a single dbt model that produces a clean “orders_daily” table already improves speed and trust.</blockquote><h3>Optional: Schedule your pipeline with <strong>cron</strong></h3><p>First, create a tiny wrapper script so cron doesn’t have to know about your virtualenv or paths.</p><p>Create run_snapshot.sh in your project root:</p><pre>#!/usr/bin/env bash<br>set -euo pipefail<br><br># 1) go to project folder<br>cd /home/monkey/Projects/pg-replica-project<br><br># 2) activate venv<br>source .venv/bin/activate<br><br># 3) export any runtime env vars (optional)<br>export LOOKBACK_DAYS=1<br><br># 4) run checks then snapshot (fail fast if checks fail)<br>python dq_checks.py<br>python snapshot_daily.py &gt;&gt; logs/snapshot.log 2&gt;&amp;1</pre><p>Make it executable and create a logs folder:</p><pre>chmod +x /home/monkey/Projects/pg-replica-project/run_snapshot.sh<br>mkdir -p /home/monkey/Projects/pg-replica-project/logs</pre><p>Now add a <strong>crontab</strong> entry (runs every day at 01:10 local time):</p><pre>crontab -e</pre><p>Add:</p><pre># m h  dom mon dow   command<br>10 1 * * * /usr/bin/flock -n /tmp/snapshot.lock \<br>/bin/bash -lc &#39;/home/monkey/Projects/pg-replica-project/run_snapshot.sh&#39;</pre><p>That’s it, cron will:</p><ul><li>Enter your project, activate the venv, run dq_checks.py, then snapshot_daily.py</li><li>log output to logs/snapshot.log</li><li>use flock so runs don’t overlap if one is still going at the next schedule</li></ul><blockquote>Remember, change schedule (examples):</blockquote><blockquote>→ */30 * * * * → every 30 minutes</blockquote><blockquote>→ 5 2 * * 1-5 → weekdays at 02:05</blockquote><blockquote>→ 0 0 1 * * → first of the month at midnight</blockquote><h3>Evolving this setup for real teams</h3><p>As stakeholders iterate, you’ll discover edge cases, missing columns, and new calculations. Capture those in your shared doc and keep feature toggles simple. If queries on the replica get heavy, add indexes that serve analytics (safe on the replica), or offload large joins to a warehouse (BigQuery, Snowflake, Redshift) fed by the replica or by CDC. If “freshness” becomes critical (minutes), keep the replica and add CDC with Debezium or built-in logical decoding to stream changes.</p><h4>Most important takeaways</h4><ul><li>Keep analytics off production: always query a replica or warehouse.</li><li>Ship a first result fast; learn and iterate.</li><li>Write decisions, definitions, and data quirks in a living doc.</li><li>Grow tooling (dbt, Airflow, CDC) only when pain appears.</li></ul><h3>Conclusion</h3><p>An analytics environment that respects production safety and still moves fast is not about big platforms; it is about good boundaries and small steps. A read-replica gives you a low-risk runway. A simple Python layer and minimal data quality checks let you deliver value this week. Clear documentation prevents drift. When the team asks for more, you have room to scale: indexes on the replica, nightly snapshots, dbt models, scheduled exports, and later CDC. This path keeps you honest, keeps prod healthy, and keeps your partners unblocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGpnVK2BCKQSEJqkxPxFIA.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4a70a0e96a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Single-Box Lakehouse on Citi Bike Data]]></title>
            <link>https://medium.com/@thisis-Shitanshu/build-a-single-box-lakehouse-on-citi-bike-data-a8f2d0872f4e?source=rss-960d2399f388------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f2d0872f4e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Shitanshu Pandey]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 16:49:23 GMT</pubDate>
            <atom:updated>2025-09-16T16:49:23.834Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to convert CSV once, query fast, stream to ML, and scale from your laptop to a cluster</h4><p>At the very top end today, “big data” is routinely petabytes per day and exabyte-scale lakes and warehouses. A few public reference points:</p><ul><li>Meta (Facebook): exabyte-scale warehouse and an exabyte distributed filesystem (“<a href="https://distributed-computing-musings.com/2024/01/paper-notes-facebooks-tectonic-filesystem-efficiency-from-exascale/">Tectonic</a>”), spread across regions.</li><li>Netflix: migrated an exabyte-scale data lake to Apache Iceberg (<a href="https://aws.amazon.com/awstv/watch/3db41488539/">AWS re:Invent talk</a>).</li><li>Uber: Kafka handles ~7–8 PB/day; Flink ~6.5 PB/day; Presto reads ~90 PB/day (<a href="https://blog.2minutestreaming.com/p/uber-data-infrastructure-scale-numbers">recommended read</a>).</li><li>Pinterest: trains models on tens of petabytes of logs (<a href="http://medium.com/pinterest-engineering/how-pinterest-accelerates-ml-feature-iterations-via-effective-backfill-d67ea125519c">recommended read</a>).</li></ul><h3>When does “big data” start for you?</h3><p>“Big data” is not a magic size. It starts the moment your dataset or workload no longer fits comfortably on one machine with good speed and reliability. When that happens, you move from a single box to a cluster and from local disks to distributed or cloud storage. Use practical thresholds tied to a single box vs a cluster.</p><h4>1) Stay single-machine (scale-up) if</h4><ul><li>Your working set fits in RAM with 2–3× headroom. With 256–1024 GB RAM this means about 100–400 GB of in-memory analytics.</li><li>Total data is ≤ 2–5 TB and you are fine with batch or chunked processing on fast NVMe.</li><li>Your team is small, the failure blast radius is low, and you do not need multi-writer, multi-reader storage semantics.</li></ul><h4>2) Move to a cluster + distributed storage if any of these are true</h4><ul><li>A single job’s input regularly exceeds about 1–2 TB, or your daily ingest is ≥ 200–500 GB with tight SLAs.</li><li>Total lake size is ≥ 10–30 TB and multiple teams must read and write concurrently.</li><li>You need elastic compute and fault tolerance beyond one host.</li></ul><h3>A simple mental model</h3><h4>Working set</h4><p>The chunk of data you need in memory at one time. If it does not fit in RAM with safety headroom, things slow down or crash.</p><h4>Throughput and latency</h4><p>How fast you can read or write per second, and how long each operation takes. Large jobs need both high throughput and stability.</p><h4>Concurrency</h4><p>Many users and jobs reading and writing the same data need shared, fault-tolerant storage.</p><h3>What to choose in 2025</h3><p>Prefer cloud object storage with an <a href="https://medium.com/geekculture/open-table-formats-delta-iceberg-hudi-732f682ec0bb">open table format</a>. This is the modern replacement for “HDFS everywhere”.</p><ul><li>Storage: S3 or GCS or ADLS</li><li>Table format: Apache Iceberg or Delta Lake or Hudi</li><li>Query and batch: Spark or Trino or BigQuery or Snowflake</li><li>Streaming: Kafka or Pub/Sub or Event Hubs, with Flink or Spark Structured Streaming</li><li>Orchestration: Airflow or Dagster</li><li>Compute: Kubernetes or serverless services</li></ul><blockquote><strong>Why this works:</strong> compute is stateless and elastic, storage is durable and cheap, tables carry schema and version history, and many engines can share the same data.</blockquote><h3>Reality check on single-server headroom today</h3><p>A healthy “big but single” machine can have:</p><ul><li>64–256 CPU cores</li><li>0.5–2 TB RAM, and</li><li>50–200 TB NVMe with 100–400 GbE networking.</li></ul><p>That comfortably handles hundreds of GB in memory and a few TB via chunked pipelines. Once you push beyond the thresholds above, operational risk and time-to-result usually force a distributed design.</p><h3>Practical steps to evolve</h3><h4>Make files columnar now</h4><p>Save results in Parquet with sensible partitioning, even on a single machine. Your future cluster will read the same files.</p><h4>Add a table format when collaboration begins</h4><p>Wrap those Parquet folders with Iceberg or Delta to get atomic writes, schema history, and snapshots.</p><h4>Lift compute to the cluster</h4><p>Move heavy jobs to Spark or Trino. Keep small ad hoc work in DuckDB on your system that queries the same data.</p><h4>Introduce streaming only when needed</h4><p>Start with batch micro-batches. Adopt Kafka and Flink when you really need sub-minute latencies or event-time logic.</p><h3>Tuning tips that pay off</h3><ul><li>Never start from CSV if you can avoid it. Convert once to Parquet.</li><li>Partition by time first, then by a selective key.</li><li>Use ZSTD compression for Parquet.</li><li>Chunk by time. Process one day or week at a time and write outputs back to Parquet.</li><li>Avoid tiny files. Aim for 128–512 MB per Parquet file and compact small files on a schedule.</li><li>Push filters down to the storage layer. Engines will skip non-matching partitions.</li></ul><h3>Single-Box Lakehouse (what we will build here)</h3><p>Let’s get started with the practical implementation of some of our principles. We will:</p><ul><li>Convert Citi Bike CSV files → Parquet (ZSTD, partitioned by date).</li><li>Query with DuckDB and Polars using pushdown and streaming.</li><li>Keep the working set under about one-third of RAM.</li><li>Train a small PyTorch model that streams batches from Parquet.</li><li>Add cron jobs for daily ingest and weekly compaction.</li></ul><h3>Project skeleton</h3><pre>local-lakehouse/<br>├─ env/                         # Python venv (created later)<br>├─ data/<br>│  ├─ raw/                      # raw CSV landing zone (Citi Bike downloads)<br>│  └─ parquet/                  # partitioned Parquet lake<br>│     └─ date=YYYY-MM-DD/<br>├─ duckdb/<br>│  ├─ ingest.sql<br>│  └─ queries.sql<br>├─ scripts/<br>│  ├─ 00_download_raw.sh<br>│  ├─ 01_csv_to_parquet_duckdb.py<br>│  ├─ 02_duckdb_examples.py<br>│  ├─ 03_polars_examples.py<br>│  ├─ 04_compact_parquet.py<br>│  ├─ 05_train_torch_streaming.py<br>│  └─ utils.py<br>├─ requirements.txt<br>└─ README.md</pre><h4>requirements.txt</h4><pre>duckdb==1.0.0<br>polars[all]==1.5.0<br>pyarrow&gt;=15.0.0<br>zstandard<br>psutil<br>torch==2.3.0<br>numpy</pre><h3>Setup</h3><pre>mkdir -p local-lakehouse/{data/raw,data/parquet,duckdb,scripts}<br>cd local-lakehouse<br><br>python3 -m venv env<br>source env/bin/activate<br>pip install -U pip<br>pip install -r requirements.txt</pre><p>Set two environment variables we will reuse:</p><pre>export LAKE=$(pwd)/data/parquet<br>export RAW=$(pwd)/data/raw</pre><h3>Get sample data (Citi Bike trip data)</h3><p>We will download Citi Bike trip CSV files from the official S3 index at <a href="https://s3.amazonaws.com/tripdata/index.html">https://s3.amazonaws.com/tripdata/index.html</a>. The file names have changed over the years, so the script below parses the index page and picks the right links for the months you choose.</p><h4>scripts/00_download_raw.sh</h4><pre>#!/usr/bin/env bash<br># Usage:<br>#   scripts/00_download_raw.sh 2024-01 2024-02 2024-03<br>#   scripts/00_download_raw.sh 202401 202402 202403<br>#   scripts/00_download_raw.sh 2023            # full-year zip<br># Months default (if no args): 2024-01..2024-03<br><br>set -euo pipefail<br>: &quot;${RAW:?RAW env var not set}&quot;<br><br>BASE=&quot;https://s3.amazonaws.com/tripdata&quot;<br><br># If no args, pick a small default set<br>if [ &quot;$#&quot; -eq 0 ]; then<br>  ARGS=( &quot;2024-01&quot; &quot;2024-02&quot; &quot;2024-03&quot; &quot;2024-04&quot; &quot;2024-05&quot; &quot;2024-06&quot;)<br>else<br>  ARGS=( &quot;$@&quot; )<br>fi<br><br>have_cmd() { command -v &quot;$1&quot; &gt;/dev/null 2&gt;&amp;1; }<br>have_cmd curl || { echo &quot;curl not found&quot;; exit 1; }<br>have_cmd unzip || { echo &quot;unzip not found (sudo apt-get install unzip)&quot;; exit 1; }<br><br># Returns 0 if URL exists (HEAD succeeds)<br>url_exists() {<br>  curl -sSfIL &quot;$1&quot; &gt;/dev/null 2&gt;&amp;1<br>}<br><br>download() {<br>  local url=&quot;$1&quot; out=&quot;$2&quot;<br>  echo &quot;Downloading $url&quot;<br>  curl -L --fail --retry 3 --retry-delay 2 &quot;$url&quot; -o &quot;$out&quot;<br>}<br><br>mkdir -p &quot;$RAW&quot;<br><br>for token in &quot;${ARGS[@]}&quot;; do<br>  # Normalize input<br>  # Accept YYYY, YYYY-MM, or YYYYMM<br>  if [[ &quot;$token&quot; =~ ^[0-9]{4}$ ]]; then<br>    Y=&quot;$token&quot;<br>    KIND=&quot;YEAR&quot;<br>  elif [[ &quot;$token&quot; =~ ^([0-9]{4})-([0-9]{2})$ ]]; then<br>    Y=&quot;${BASH_REMATCH[1]}&quot;<br>    M=&quot;${BASH_REMATCH[2]}&quot;<br>    KIND=&quot;MONTH&quot;<br>  elif [[ &quot;$token&quot; =~ ^([0-9]{6})$ ]]; then<br>    Y=&quot;${token:0:4}&quot;<br>    M=&quot;${token:4:2}&quot;<br>    KIND=&quot;MONTH&quot;<br>  else<br>    echo &quot;Unrecognized token: $token  (use YYYY, YYYY-MM, or YYYYMM)&quot;; continue<br>  fi<br><br>  CANDIDATES=()<br><br>  if [ &quot;$KIND&quot; = &quot;YEAR&quot; ]; then<br>    # e.g. 2023-citibike-tripdata.zip<br>    CANDIDATES+=( &quot;$BASE/${Y}-citibike-tripdata.zip&quot; )<br>  else<br>    # MONTH candidates (handle both naming styles and csv/no-csv)<br>    # e.g. 202401-citibike-tripdata.zip, 202401-citibike-tripdata.csv.zip,<br>    #      2024-01-citibike-tripdata.zip, 2024-01-citibike-tripdata.csv.zip<br>    CANDIDATES+=(<br>      &quot;$BASE/${Y}${M}-citibike-tripdata.zip&quot;<br>      &quot;$BASE/${Y}${M}-citibike-tripdata.csv.zip&quot;<br>      &quot;$BASE/${Y}-${M}-citibike-tripdata.zip&quot;<br>      &quot;$BASE/${Y}-${M}-citibike-tripdata.csv.zip&quot;<br>    )<br>  fi<br><br>  FOUND=&quot;&quot;<br>  for url in &quot;${CANDIDATES[@]}&quot;; do<br>    if url_exists &quot;$url&quot;; then FOUND=&quot;$url&quot;; break; fi<br>  done<br><br>  if [ -z &quot;$FOUND&quot; ]; then<br>    echo &quot;No file found for $token (tried: ${CANDIDATES[*]})&quot;<br>    continue<br>  fi<br><br>  fname=&quot;$(basename &quot;$FOUND&quot;)&quot;<br>  out=&quot;$RAW/$fname&quot;<br>  download &quot;$FOUND&quot; &quot;$out&quot;<br><br>  case &quot;$out&quot; in<br>    *.zip|*.csv.zip)<br>      echo &quot;Unzipping $out → $RAW&quot;<br>      unzip -o -d &quot;$RAW&quot; &quot;$out&quot; &gt;/dev/null<br>      ;;<br>    *.csv)<br>      # already plain CSV<br>      ;;<br>    *)<br>      echo &quot;Downloaded $out (unknown extension); inspect manually.&quot;<br>      ;;<br>  esac<br>done<br><br>echo &quot;Done. Raw files are in $RAW&quot;</pre><p>Make it executable and run it:</p><pre>chmod +x scripts/00_download_raw.sh<br>./scripts/00_download_raw.sh</pre><p>You will now have a mix of .csv files inside data/raw/. Older months may come from inside .zip archives.</p><h3>Convert CSV → Parquet (ZSTD, partitioned by date)</h3><p>We will use DuckDB because it can stream large CSVs, parse timestamps, compute derived columns, and write partitioned Parquet with compression and sensible row groups.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuHm6FEb2Re4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuHm6FEb2Re4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuHm6FEb2Re4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7189c711a218277dd277eef7193cd9a/href">https://medium.com/media/c7189c711a218277dd277eef7193cd9a/href</a></iframe><h4>Handle schema drift across years</h4><p>Citi Bike column names vary across years. We normalize to a canonical schema:</p><ul><li>started_at, ended_at as timestamps</li><li>start_station_id, end_station_id as text</li><li>start_lat, start_lng, end_lat, end_lng as doubles</li><li>member_type as text (maps from member_casual or usertype)</li><li>Derived columns: date, start_hour, is_weekend, duration_min, distance_km (Haversine)</li></ul><p>We generate SQL per file, based on the header names DuckDB will see.</p><h4>duckdb/ingest.sql</h4><pre>PRAGMA threads=4;<br>PRAGMA memory_limit=&#39;8GB&#39;;<br><br>/* 1) Load raw CSV (auto-detect types; skip rare bad rows) */<br>CREATE OR REPLACE TABLE trips_stage AS<br>SELECT<br>  CAST(${COL_STARTED_AT} AS TIMESTAMP)  AS started_at,<br>  CAST(${COL_ENDED_AT}   AS TIMESTAMP)  AS ended_at,<br>  CAST(${COL_SID_START}  AS VARCHAR)    AS start_station_id,<br>  CAST(${COL_SID_END}    AS VARCHAR)    AS end_station_id,<br>  CAST(${COL_LAT_START}  AS DOUBLE)     AS start_lat,<br>  CAST(${COL_LNG_START}  AS DOUBLE)     AS start_lng,<br>  CAST(${COL_LAT_END}    AS DOUBLE)     AS end_lat,<br>  CAST(${COL_LNG_END}    AS DOUBLE)     AS end_lng,<br>  CAST(${COL_MEMBER}     AS VARCHAR)    AS member_type<br>FROM read_csv_auto(&#39;${RAW_FILE}&#39;, SAMPLE_SIZE=-1, IGNORE_ERRORS=TRUE);<br><br>/* 2) Enrich with derived columns */<br>CREATE OR REPLACE TABLE trips_enriched AS<br>SELECT<br>  *,<br>  CAST(started_at AS DATE)                                         AS date,<br>  EXTRACT(HOUR FROM started_at)                                    AS start_hour,<br>  CASE WHEN EXTRACT(DOW FROM started_at) IN (0,6) THEN 1 ELSE 0 END AS is_weekend,<br>  GREATEST(0, DATE_DIFF(&#39;second&#39;, started_at, ended_at) / 60.0)    AS duration_min,<br>  CASE<br>    WHEN start_lat IS NULL OR start_lng IS NULL OR end_lat IS NULL OR end_lng IS NULL THEN NULL<br>    ELSE 2 * 6371.0 * ASIN(<br>      SQRT(<br>        POW(SIN(RADIANS((end_lat - start_lat) / 2)), 2) +<br>        COS(RADIANS(start_lat)) * COS(RADIANS(end_lat)) *<br>        POW(SIN(RADIANS((end_lng - start_lng) / 2)), 2)<br>      )<br>    )<br>  END                                                             AS distance_km<br>FROM trips_stage;<br><br>/* 3) Write Parquet, partitioned by date (no WITH; string option values) */<br>COPY trips_enriched<br>TO &#39;${OUT_DIR}&#39;<br>(FORMAT &#39;parquet&#39;,<br> PARTITION_BY (date),<br> COMPRESSION &#39;zstd&#39;,<br> ROW_GROUP_SIZE 1280000);</pre><h4>scripts/01_csv_to_parquet_duckdb.py</h4><pre>import os, glob, gzip, shutil, csv<br>import duckdb<br><br>LAKE = os.environ.get(&quot;LAKE&quot;)<br>RAW = os.environ.get(&quot;RAW&quot;)<br>assert LAKE and RAW<br><br>con = duckdb.connect()<br>con.execute(&quot;PRAGMA threads=4;&quot;)<br>con.execute(&quot;PRAGMA memory_limit=&#39;8GB&#39;;&quot;)<br><br>CANDIDATES = {<br>    &quot;started_at&quot;: [&quot;started_at&quot;,&quot;starttime&quot;,&quot;Start Time&quot;,&quot;start_time&quot;],<br>    &quot;ended_at&quot;:   [&quot;ended_at&quot;,&quot;stoptime&quot;,&quot;Stop Time&quot;,&quot;end_time&quot;],<br>    &quot;sid_start&quot;:  [&quot;start_station_id&quot;,&quot;start station id&quot;,&quot;Start Station ID&quot;,&quot;start station id&quot;],<br>    &quot;sid_end&quot;:    [&quot;end_station_id&quot;,&quot;end station id&quot;,&quot;End Station ID&quot;,&quot;end station id&quot;],<br>    &quot;lat_start&quot;:  [&quot;start_lat&quot;,&quot;start station latitude&quot;,&quot;Start Station Latitude&quot;],<br>    &quot;lng_start&quot;:  [&quot;start_lng&quot;,&quot;start station longitude&quot;,&quot;Start Station Longitude&quot;],<br>    &quot;lat_end&quot;:    [&quot;end_lat&quot;,&quot;end station latitude&quot;,&quot;End Station Latitude&quot;],<br>    &quot;lng_end&quot;:    [&quot;end_lng&quot;,&quot;end station longitude&quot;,&quot;End Station Longitude&quot;],<br>    &quot;member&quot;:     [&quot;member_casual&quot;,&quot;usertype&quot;,&quot;User Type&quot;,&quot;member_type&quot;],<br>}<br><br>def quote_ident(col):<br>    col = col.replace(&#39;&quot;&#39;,&#39;&quot;&quot;&#39;)<br>    return f&#39;&quot;{col}&quot;&#39;<br><br>def pick(headers, options, required=False):<br>    for o in options:<br>        if o in headers:<br>            return quote_ident(o)<br>    if required:<br>        raise ValueError(f&quot;Required column not found. Tried: {options}&quot;)<br>    return &quot;NULL&quot;<br><br>def detect_columns(csv_path):<br>    with open(csv_path, &quot;r&quot;, newline=&quot;&quot;, encoding=&quot;utf-8-sig&quot;) as f:<br>        reader = csv.reader(f)<br>        headers = [h.strip() for h in next(reader)]<br>    hdrset = set(headers)<br>    return {<br>        &quot;COL_STARTED_AT&quot;: pick(hdrset, CANDIDATES[&quot;started_at&quot;], required=True),<br>        &quot;COL_ENDED_AT&quot;:   pick(hdrset, CANDIDATES[&quot;ended_at&quot;],   required=True),<br>        &quot;COL_SID_START&quot;:  pick(hdrset, CANDIDATES[&quot;sid_start&quot;]),<br>        &quot;COL_SID_END&quot;:    pick(hdrset, CANDIDATES[&quot;sid_end&quot;]),<br>        &quot;COL_LAT_START&quot;:  pick(hdrset, CANDIDATES[&quot;lat_start&quot;]),<br>        &quot;COL_LNG_START&quot;:  pick(hdrset, CANDIDATES[&quot;lng_start&quot;]),<br>        &quot;COL_LAT_END&quot;:    pick(hdrset, CANDIDATES[&quot;lat_end&quot;]),<br>        &quot;COL_LNG_END&quot;:    pick(hdrset, CANDIDATES[&quot;lng_end&quot;]),<br>        &quot;COL_MEMBER&quot;:     pick(hdrset, CANDIDATES[&quot;member&quot;]),<br>    }<br><br>def load_sql_template():<br>    with open(&quot;duckdb/ingest.sql&quot;,&quot;r&quot;,encoding=&quot;utf-8&quot;) as f:<br>        return f.read()<br><br>def render_sql(tmpl, replacements):<br>    sql = tmpl<br>    for k, v in replacements.items():<br>        sql = sql.replace(&quot;${&quot;+k+&quot;}&quot;, v)<br>    return sql<br><br>def all_csv_files(raw_dir):<br>    return sorted(glob.glob(os.path.join(raw_dir, &quot;*.csv&quot;)))<br><br>tmpl = load_sql_template()<br>csv_files = all_csv_files(RAW)<br>if not csv_files:<br>    print(&quot;No CSV files found in&quot;, RAW)<br>    raise SystemExit(1)<br><br>for csv_path in csv_files:<br>    print(f&quot;Ingesting {csv_path}&quot;)<br><br>    # 1) fresh staging dir per file<br>    STAGE = os.path.join(LAKE, &quot;_staging_ingest&quot;)<br>    shutil.rmtree(STAGE, ignore_errors=True)<br>    os.makedirs(STAGE, exist_ok=True)<br><br>    cols = detect_columns(csv_path)<br>    repl = {<br>        **cols,<br>        &quot;RAW_FILE&quot;: csv_path.replace(&quot;&#39;&quot;, &quot;&#39;&#39;&quot;),<br>        &quot;OUT_DIR&quot;: STAGE.replace(&quot;&#39;&quot;, &quot;&#39;&#39;&quot;),<br>    }<br>    sql = render_sql(tmpl, repl)<br>    # open(&#39;last_ingest.sql&#39;,&#39;w&#39;).write(sql)  # optional debug<br>    con.execute(sql)<br><br>    # 2) move each written partition into LAKE, replacing if exists<br>    for part in glob.glob(os.path.join(STAGE, &quot;date=*&quot;)):<br>        dst = os.path.join(LAKE, os.path.basename(part))<br>        shutil.rmtree(dst, ignore_errors=True)<br>        shutil.move(part, dst)<br><br>    shutil.rmtree(STAGE, ignore_errors=True)<br><br>print(&quot;Done. Parquet written/merged into&quot;, LAKE)</pre><p>Run it:</p><pre>python scripts/01_csv_to_parquet_duckdb.py</pre><p>You will get folders like:</p><pre>data/parquet/date=2023-01-01/part-0000.parquet<br>...</pre><p><strong>Why this matters</strong></p><ul><li>ZSTD gives smaller files without hurting read speed.</li><li>Partitioning by date lets engines skip non-matching folders.</li><li>Row groups near about 128 MB help scanners read sequentially and avoid tiny files.</li></ul><h3>Query with DuckDB (pushdown + low memory)</h3><h4><strong>duckdb/queries.sql</strong></h4><pre>PRAGMA threads=4;<br>PRAGMA memory_limit=&#39;8GB&#39;;<br><br>-- 4.1 projection and predicate pushdown (read only needed columns and days)<br>-- Count trips per day for January 2024 where duration is between 2 and 120 minutes<br>SELECT date, COUNT(*) AS trips<br>FROM read_parquet(&#39;${LAKE}/date=2024-01-*/**.parquet&#39;)<br>WHERE duration_min BETWEEN 2 AND 120<br>GROUP BY date<br>ORDER BY date;<br><br>-- 4.2 example: average duration by start_station_id for February 2024<br>SELECT start_station_id, AVG(duration_min) AS avg_duration_min<br>FROM read_parquet(&#39;${LAKE}/date=2024-02-*/**.parquet&#39;)<br>WHERE duration_min &gt; 1 AND duration_min &lt; 180<br>GROUP BY start_station_id<br>ORDER BY avg_duration_min DESC<br>LIMIT 20;</pre><h4>scripts/02_duckdb_examples.py</h4><pre>import duckdb, os<br>LAKE = os.environ[&quot;LAKE&quot;]<br><br>con = duckdb.connect()<br>con.execute(&quot;PRAGMA threads=4;&quot;)<br>con.execute(&quot;PRAGMA memory_limit=&#39;8GB&#39;;&quot;)<br><br>q1 = f&quot;&quot;&quot;<br>SELECT date, COUNT(*) AS trips<br>FROM read_parquet(&#39;{LAKE}/date=2024-01-*/**.parquet&#39;)<br>WHERE duration_min BETWEEN 2 AND 120<br>GROUP BY date<br>ORDER BY date;<br>&quot;&quot;&quot;<br>print(con.execute(q1).df().head())<br><br>q2 = f&quot;&quot;&quot;<br>SELECT start_station_id, AVG(duration_min) AS avg_duration_min<br>FROM read_parquet(&#39;{LAKE}/date=2024-02-*/**.parquet&#39;)<br>WHERE duration_min &gt; 1 AND duration_min &lt; 180<br>GROUP BY start_station_id<br>ORDER BY avg_duration_min DESC<br>LIMIT 20;<br>&quot;&quot;&quot;<br>print(con.execute(q2).df())</pre><p>Run:</p><pre>python scripts/02_duckdb_examples.py</pre><p>DuckDB scans only relevant columns and partitions, so memory stays low.</p><h3>Query with Polars using lazy + streaming</h3><h4>scripts/03_polars_examples.py</h4><pre>import os, psutil, glob<br>import polars as pl<br><br>LAKE = os.environ[&quot;LAKE&quot;]<br><br>def rss_gb():<br>    return psutil.Process().memory_info().rss / 1024**3<br><br># --- JANUARY QUERY ---<br># Our files live in: {LAKE}/date=YYYY-MM-DD/part-*.parquet<br>jan_files = sorted(glob.glob(os.path.join(LAKE, &quot;date=2024-01-*&quot;, &quot;*.parquet&quot;)))<br>if not jan_files:<br>    raise SystemExit(f&quot;No Parquet files matched pattern: {LAKE}/date=2024-01-*/*.parquet&quot;)<br><br>scan = pl.scan_parquet(jan_files, low_memory=True)<br><br>q = (<br>    scan.select([&quot;date&quot;, &quot;duration_min&quot;])<br>        .filter((pl.col(&quot;duration_min&quot;) &gt;= 2) &amp; (pl.col(&quot;duration_min&quot;) &lt;= 120))<br>        .group_by(&quot;date&quot;)<br>        .len()<br>        .sort(&quot;date&quot;)<br>)<br><br>print(&quot;RSS before:&quot;, rss_gb(), &quot;GB&quot;)<br>out = q.collect(streaming=True)<br>print(&quot;RSS after :&quot;, rss_gb(), &quot;GB&quot;)<br>print(out.head(5))<br><br># --- JAN–MAR EXAMPLE ---<br>q1_3_files = sorted(glob.glob(os.path.join(LAKE, &quot;date=2024-0[1-3]-*&quot;, &quot;*.parquet&quot;)))<br>if not q1_3_files:<br>    raise SystemExit(f&quot;No Parquet files matched pattern: {LAKE}/date=2024-0[1-3]-*/*.parquet&quot;)<br><br>scan2 = pl.scan_parquet(q1_3_files, low_memory=True)<br>result = (<br>    scan2<br>    .select([&quot;start_station_id&quot;, &quot;duration_min&quot;])<br>    .filter((pl.col(&quot;duration_min&quot;) &gt; 1) &amp; (pl.col(&quot;duration_min&quot;) &lt; 180))<br>    .group_by([&quot;start_station_id&quot;])<br>    .agg(pl.col(&quot;duration_min&quot;).mean().alias(&quot;avg_duration_min&quot;))<br>    .sort(&quot;avg_duration_min&quot;, descending=True)<br>    .limit(20)<br>    .collect(streaming=True)<br>)<br>print(result)</pre><p>Run:</p><pre>python scripts/03_polars_examples.py</pre><h3>Weekly compaction to avoid tiny files</h3><p>If you have many small parts per day, rewrite them as fewer larger files.</p><h4><strong>scripts/04_compact_parquet.py</strong></h4><pre>import os, glob, shutil, math<br>import polars as pl<br><br>LAKE = os.environ[&quot;LAKE&quot;]<br>OUT = os.path.join(LAKE, &quot;_compact&quot;)<br>os.makedirs(OUT, exist_ok=True)<br><br># Adjust this to the week you want to compact<br># e.g., if your data is 2024 Jan:<br>days = sorted(glob.glob(os.path.join(LAKE, &quot;date=2024-01-0[1-7]&quot;)))<br># for 2023: days = sorted(glob.glob(os.path.join(LAKE, &quot;date=2023-01-0[1-7]&quot;)))<br><br>TARGET_MB = 256  # aim for ~256 MB per output file<br><br>for day_path in days:<br>    day = os.path.basename(day_path).split(&quot;=&quot;)[1]<br>    print(&quot;Compacting&quot;, day)<br><br>    files = sorted(glob.glob(os.path.join(day_path, &quot;*.parquet&quot;)))<br>    if not files:<br>        print(f&quot;  No parquet files under {day_path}, skipping.&quot;)<br>        continue<br><br>    # Lazy scan then collect with streaming to keep memory in check<br>    scan = pl.scan_parquet(files, low_memory=True)<br>    df = scan.collect(streaming=True).rechunk()<br><br>    # Decide how many files to write for ~TARGET_MB each (best-effort)<br>    # estimated_size() returns bytes for in-memory dataframe<br>    est_bytes = getattr(df, &quot;estimated_size&quot;, None)<br>    if callable(est_bytes):<br>        size_bytes = df.estimated_size()<br>        n_files = max(1, math.ceil(size_bytes / (TARGET_MB * 1024 * 1024)))<br>    else:<br>        n_files = 1  # fallback if method not available<br><br>    out_day = os.path.join(OUT, f&quot;date={day}&quot;)<br>    shutil.rmtree(out_day, ignore_errors=True)<br>    os.makedirs(out_day, exist_ok=True)<br><br>    if n_files == 1:<br>        df.write_parquet(<br>            os.path.join(out_day, &quot;part-0000.parquet&quot;),<br>            use_pyarrow=True,<br>            compression=&quot;zstd&quot;,<br>            statistics=True,<br>            row_group_size=1_280_000,  # ~128 MB row groups<br>        )<br>    else:<br>        chunk_len = math.ceil(len(df) / n_files)<br>        for i in range(n_files):<br>            start = i * chunk_len<br>            if start &gt;= len(df):<br>                break<br>            end = min((i + 1) * chunk_len, len(df))<br>            df_slice = df.slice(start, end - start)<br>            df_slice.write_parquet(<br>                os.path.join(out_day, f&quot;part-{i:04d}.parquet&quot;),<br>                use_pyarrow=True,<br>                compression=&quot;zstd&quot;,<br>                statistics=True,<br>                row_group_size=1_280_000,<br>            )<br><br>print(&quot;Switching compacted week into place&quot;)<br>for day_path in glob.glob(os.path.join(OUT, &quot;date=*&quot;)):<br>    dst = os.path.join(LAKE, os.path.basename(day_path))<br>    shutil.rmtree(dst, ignore_errors=True)<br>    shutil.move(day_path, dst)<br><br>shutil.rmtree(OUT, ignore_errors=True)<br>print(&quot;Compaction complete.&quot;)</pre><blockquote><strong>Run weekly via cron.</strong></blockquote><h3>Streaming training with PyTorch (no giant DataFrame)</h3><p>We will build an IterableDataset that scans Parquet files in batches and yields tensors. The model will predict duration_min from simple numeric features (start_hour, is_weekend, distance_km). Replace with your own features as needed.</p><h4><strong>scripts/utils.py</strong></h4><pre>import os, glob<br>import pyarrow.dataset as ds<br>import numpy as np<br>import torch<br><br>def _expand_parquet_paths(root_glob: str):<br>    &quot;&quot;&quot;Return a sorted list of parquet files for Arrow; supports dirs or glob patterns.&quot;&quot;&quot;<br>    if os.path.isdir(root_glob):<br>        # recurse and collect *.parquet<br>        paths = []<br>        for dp, _, files in os.walk(root_glob):<br>            for f in files:<br>                if f.endswith(&quot;.parquet&quot;):<br>                    paths.append(os.path.join(dp, f))<br>        paths.sort()<br>    else:<br>        # if pattern points to date folders, ensure we look for files inside them<br>        patt = root_glob<br>        if not patt.endswith(&quot;.parquet&quot;):<br>            patt = os.path.join(patt.rstrip(&quot;/&quot;), &quot;*.parquet&quot;)<br>        paths = sorted(glob.glob(patt))<br>    if not paths:<br>        raise FileNotFoundError(<br>            f&quot;No Parquet files matched &#39;{root_glob}&#39;. &quot;<br>            &quot;Try a pattern like: $LAKE/date=2024-0[1-3]-*/*.parquet&quot;<br>        )<br>    return paths<br><br>def parquet_batches(root_glob, columns, batch_rows=65536, predicate=None):<br>    paths = _expand_parquet_paths(root_glob)<br>    dataset = ds.dataset(paths, format=&quot;parquet&quot;)<br>    scanner = dataset.scanner(columns=columns, filter=predicate, batch_size=batch_rows)<br>    for rb in scanner.to_batches():<br>        batch = {c: rb.column(i).to_numpy(zero_copy_only=False) for i, c in enumerate(columns)}<br>        yield batch<br><br>class CitiIterableDataset(torch.utils.data.IterableDataset):<br>    def __init__(self, root_glob, feature_cols, label_col, batch_rows=65536):<br>        super().__init__()<br>        self.root_glob = root_glob<br>        self.feature_cols = feature_cols<br>        self.label_col = label_col<br>        self.batch_rows = batch_rows<br><br>    def __iter__(self):<br>        cols = self.feature_cols + [self.label_col]<br>        for batch in parquet_batches(self.root_glob, cols, batch_rows=self.batch_rows):<br>            mask = np.isfinite(batch[self.label_col])<br>            for c in self.feature_cols:<br>                mask &amp;= np.isfinite(batch[c])<br>            X = np.stack([batch[c][mask].astype(np.float32, copy=False) for c in self.feature_cols], axis=1)<br>            y = batch[self.label_col][mask].astype(np.float32, copy=False)<br>            yield torch.from_numpy(X), torch.from_numpy(y)</pre><h4><strong>scripts/05_train_torch_streaming.py</strong></h4><pre>import os, torch, torch.nn as nn, torch.optim as optim<br>from utils import CitiIterableDataset<br><br>LAKE = os.environ[&quot;LAKE&quot;]<br><br># Features prepared during ingest<br>FEATURES = [&quot;start_hour&quot;, &quot;is_weekend&quot;, &quot;distance_km&quot;]<br>LABEL = &quot;duration_min&quot;<br><br># Train on the months you downloaded<br>train_glob = f&quot;{LAKE}/date=2024-0[1-3]-*/*.parquet&quot;  # adjust freely<br><br>dataset = CitiIterableDataset(train_glob, FEATURES, LABEL, batch_rows=65536)<br>loader = torch.utils.data.DataLoader(dataset, batch_size=None)  # already batched<br><br># Simple MLP<br>model = nn.Sequential(<br>    nn.Linear(len(FEATURES), 16),<br>    nn.ReLU(),<br>    nn.Linear(16, 1)<br>)<br>loss_fn = nn.L1Loss()<br>opt = optim.Adam(model.parameters(), lr=1e-3)<br><br>model.train()<br>steps, running = 0, 0.0<br>for X, y in loader:<br>    opt.zero_grad()<br>    pred = model(X).squeeze(1)<br>    loss = loss_fn(pred, y)<br>    loss.backward()<br>    opt.step()<br><br>    steps += 1<br>    running += float(loss)<br>    if steps % 100 == 0:<br>        print(f&quot;step {steps}, avg L1 loss {running/100:.3f}&quot;)<br>        running = 0.0<br>        if steps &gt;= 800:  # keep training brief on a laptop<br>            break<br><br>print(&quot;Done training.&quot;)</pre><p>This never materializes the whole dataset in memory. It reads record batches from Parquet and hands them to the model.</p><h3>Working-set hygiene</h3><ul><li>DuckDB: PRAGMA memory_limit=&#39;8GB&#39;; PRAGMA threads=4;</li><li>Polars: always .scan_parquet(..., low_memory=True) and .collect(streaming=True)</li><li>If RSS climbs past about 12 GB on a 16 GB box, switch that step to a streaming plan or reduce parallelism.</li></ul><h3>Automate with cron</h3><p>Daily ingest at 03:00 (download and convert):</p><pre>crontab -e</pre><p>Add:</p><pre>0 3 * * * cd /path/to/local-lakehouse &amp;&amp; source env/bin/activate &amp;&amp; ./scripts/00_download_raw.sh &gt;&gt; logs/downloader.log 2&gt;&amp;1<br>30 3 * * * cd /path/to/local-lakehouse &amp;&amp; source env/bin/activate &amp;&amp; python scripts/01_csv_to_parquet_duckdb.py &gt;&gt; logs/ingest.log 2&gt;&amp;1</pre><p>Weekly compaction on Sundays at 04:00:</p><pre>0 4 * * 0 cd /path/to/local-lakehouse &amp;&amp; source env/bin/activate &amp;&amp; python scripts/04_compact_parquet.py &gt;&gt; logs/compact.log 2&gt;&amp;1</pre><p>Create the logs folder:</p><pre>mkdir -p logs</pre><h3>Next: stretch goals to reach 100–300 GB practice</h3><ul><li>Download more months to scale up. You can reach 100+ GB quickly.</li><li>Add small dimension data such as holidays or weather, and practice joins.</li><li>Add Trino or DuckDB HTTPFS to read directly from cloud object storage.</li><li>Swap PyTorch with TensorFlow. Use tf.data.Dataset.from_generator to wrap the same Parquet batch iterator.</li></ul><h3>Conclusion</h3><p>Clean rules you are practicing:</p><ul><li>Convert CSV once. Keep everything Parquet with ZSTD.</li><li>Partition by date. Read only what you need.</li><li>Use engines that push filters and columns down to the files.</li><li>Stream whenever the working set is close to RAM limits.</li><li>Compact small files on a schedule to keep scans fast.</li></ul><p>Run order recap:</p><pre># one-time<br>python -m venv env &amp;&amp; source env/bin/activate<br>pip install -r requirements.txt<br><br># daily or ad hoc<br>./scripts/00_download_raw.sh<br>python scripts/01_csv_to_parquet_duckdb.py<br><br># explore<br>python scripts/02_duckdb_examples.py<br>python scripts/03_polars_examples.py<br><br># train<br>python scripts/05_train_torch_streaming.py<br><br># weekly<br>python scripts/04_compact_parquet.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b_C8Bt53qKU2ZITxfoQSw.png" /></figure><p><em>For more insightful articles on programming and technology, follow </em><a href="https://medium.com/u/960d2399f388"><em>Shitanshu Pandey</em></a><em> on Medium.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f2d0872f4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>