<?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"><channel><title><![CDATA[Sparsh Prajapati]]></title><description><![CDATA[Sparsh Prajapati]]></description><link>https://sparshprajapati.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:49:44 GMT</lastBuildDate><atom:link href="https://sparshprajapati.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Six AI agents run a software team. The seventh rewrites their rules]]></title><description><![CDATA[tags: ai, llm, agents, python Multi-agent demos usually stop at "the agents talked to each other and produced something". I wanted to know what happens on…]]></description><link>https://sparshprajapati.hashnode.dev/six-ai-agents-run-a-software-team-the-seventh-rewrites-their-rules</link><guid isPermaLink="true">https://sparshprajapati.hashnode.dev/six-ai-agents-run-a-software-team-the-seventh-rewrites-their-rules</guid><dc:creator><![CDATA[Sparsh Prajapati]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:45:58 GMT</pubDate><content:encoded><![CDATA[<p>tags: ai, llm, agents, python</p>
<p><br />Multi-agent demos usually stop at "the agents talked to each other and produced something". I wanted to know what happens on the second run. If an agent made a mistake, does the system learn from it, or does it make the same mistake forever?</p>
<p>AI Factory is my experiment in that. It is open source: <a href="https://github.com/prajapatisparsh/AI-factory">github.com/prajapatisparsh/AI-factory</a>. It is written in Python with a Streamlit interface, and it runs on Groq and Gemini models.</p>
<h2>The team</h2>
<p>Six agents each play one role in a small software team:</p>
<ul>
<li><strong>PM</strong> writes the product requirements (the PRD).</li>
<li><strong>Tech Lead</strong> turns them into a technical plan.</li>
<li><strong>Dev</strong> writes the code.</li>
<li><strong>QA</strong> writes the tests.</li>
<li><strong>Reviewer</strong> reviews the result.</li>
<li><strong>Coach</strong> watches how the others performed and changes how they work.</li>
</ul>
<p>Each agent's behaviour comes from a plain markdown rules file, for example <code>agents/qa/rules.md</code>. The rules are data, not code, and that is what makes the next part possible.</p>
<h2>The loop: evaluate, then rewrite the rules</h2>
<p>After a run, an evaluator scores the output. The Coach reads the evaluation, finds which agent caused the weakest part, and edits that agent's rules file. The next run uses the new rules.</p>
<p>Here is a real change from one run. The evaluator found that QA's tests skipped edge cases. The Coach rewrote QA's test-planning rule:</p>
<pre><code class="language-diff">  ## Test planning
- Write test cases for the feature.
+ Write one test per acceptance criterion in the PRD.
+ Add a negative case for every user input.
+ Cite the PRD section id in each test name.
  ## Output format
</code></pre>
<p>The next run's evaluation went from 6.1 to 8.4 out of 10.</p>
<p>The new rule is better in a specific way: it is checkable. "Write test cases" can't be verified. "One test per acceptance criterion, cite the section id" can be, by the evaluator and by a human reading the diff.</p>
<h2>Why rules files instead of fine-tuning</h2>
<ul>
<li><strong>You can read every change.</strong> Each improvement is a diff in a markdown file. If the Coach makes a rule worse, you can see it and revert it, like any other commit.</li>
<li><strong>Changes are small and local.</strong> The Coach changes one agent's rules at a time, so a regression is easy to trace to its cause.</li>
<li><strong>It costs nothing to train.</strong> The models stay the same; only their instructions improve.</li>
</ul>
<h2>What I learned</h2>
<ul>
<li><strong>An agent system is only as good as its evaluator.</strong> If the score rewards the wrong thing, the Coach will optimise for the wrong thing with real enthusiasm.</li>
<li><strong>Specific rules beat clever prompts.</strong> Most improvements came from turning vague instructions into checkable ones.</li>
<li><strong>Keep a human in the loop for rule changes</strong> that touch more than one agent. Small, reviewable diffs make that cheap.</li>
</ul>
<p>The code is on GitHub, and there is a short interactive version of the rule diff on my portfolio.</p>
<hr />
<p><em>I'm Sparsh Prajapati, a full-stack engineer at Cloudzent in Gurugram, India. More of my work: <a href="https://sparshprajapati.com">sparshprajapati.com</a> · <a href="https://www.linkedin.com/in/prajapatisparsh/">LinkedIn</a> · <a href="https://github.com/prajapatisparsh">GitHub</a></em></p>
]]></content:encoded></item><item><title><![CDATA[Moving 37 million rows over a connection that drops]]></title><description><![CDATA[A publicly listed Indian steel manufacturer kept its sales history in SQL Server: 37 million rows. I was building a CRM intelligence layer on top of it…]]></description><link>https://sparshprajapati.hashnode.dev/moving-37-million-rows-over-a-connection-that-drops</link><guid isPermaLink="true">https://sparshprajapati.hashnode.dev/moving-37-million-rows-over-a-connection-that-drops</guid><dc:creator><![CDATA[Sparsh Prajapati]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:45:12 GMT</pubDate><content:encoded><![CDATA[<p>A publicly listed Indian steel manufacturer kept its sales history in SQL Server: 37 million rows. I was building a CRM intelligence layer on top of it (lead scoring, plus a different view for each of 12 roles from field officer to CMO), and that layer runs on PostgreSQL. So the first job was getting 37 million rows from SQL Server into Postgres.</p>
<p>The hard part was not the volume. It was the link. The connection between the two databases dropped, and a long copy that dies at row 21 million either starts over, or worse, restarts halfway and writes the same rows twice.</p>
<p>The rule I set was simple: pull the plug at any moment, and the sync must recover with zero duplicates and no lost rows. Here is the design that met it, built with FastAPI and SQLAlchemy.</p>
<p>Updated: the first version of this post paged by id, which can silently skip rows while the source is still taking inserts. A reader caught it with a real test; section 2 is the fix. Thank you.</p>
<ol>
<li><p>Copy in chunks, one transaction per chunk
Instead of one huge copy, the sync reads the source in fixed-size chunks. Each chunk is written to Postgres inside a single transaction. Either the whole chunk lands, or none of it does.</p>
</li>
<li><p>Page by what has committed, not by id
The first version of this post paged by primary key (WHERE id &gt; :last ORDER BY id). A reader showed why that breaks when the source is still taking inserts. Ids are handed out when a row is written, not when its transaction commits. If id 1001 is still uncommitted while 1002 commits, the reader sees 1002, the checkpoint moves past 1001, and 1001 is never copied. SQL Server under read committed snapshot isolation (RCSI, the default on Azure SQL Database) reads exactly like that, and so does Postgres. Paging by id also never revisits a row that changes after it was copied.</p>
</li>
</ol>
<p>The fix is to page by a rowversion column. SQL Server stamps every insert and update with a new value that only goes up across the whole database. MIN_ACTIVE_ROWVERSION() returns the lowest value still held by an uncommitted transaction, so reading strictly below it means the sync never steps past a gap that could still fill in.</p>
<p>Read that bound in its own statement, before the chunk query. Under RCSI a statement reads from a snapshot taken when it starts. If the bound were computed inside the same query, a transaction could commit between the snapshot and the bound, and its row would be inside the range but missing from the snapshot. Read first, the bound only covers rows that had already committed, so the next statement is guaranteed to see them.</p>
<ol start="3">
<li>Commit the checkpoint in the same transaction
This is the part that makes it resumable. A small checkpoint table in Postgres records the last rowversion that was written (a bytea column). It is updated inside the same transaction as the chunk:</li>
</ol>
<p>from sqlalchemy import text</p>
<p>def sync_chunk(src, dst, last_rv: bytes, size: int) -&gt; bytes | None:
    """src: SQL Server at READ COMMITTED (RCSI), not SNAPSHOT. dst: the Postgres engine."""
    # 1) the bound: everything below it has committed
    bound = src.execute(text("SELECT MIN_ACTIVE_ROWVERSION()")).scalar_one()
    # 2) the chunk, in a later statement whose snapshot includes all of those rows
    rows = src.execute(
        text("SELECT TOP (:n) id, account, amount, updated_at, rv FROM sales "
             "WHERE rv &gt; :last AND rv &lt; :bound ORDER BY rv"),
        {"last": last_rv, "bound": bound, "n": size},
    ).mappings().all()
    if not rows:
        return None  # caught up; run again later for new changes</p>
<pre><code>with dst.begin() as conn:  # one transaction: the rows and the checkpoint commit together
    conn.execute(
        text("INSERT INTO sales (source_id, account, amount, updated_at) "
             "VALUES (:id, :account, :amount, :updated_at) "
             "ON CONFLICT (source_id) DO UPDATE SET "
             "account = EXCLUDED.account, amount = EXCLUDED.amount, updated_at = EXCLUDED.updated_at"),
        [{k: r[k] for k in ("id", "account", "amount", "updated_at")} for r in rows],
    )
    conn.execute(
        text("UPDATE sync_checkpoint SET last_rv = :last WHERE job = 'sales'"),
        {"last": rows[-1]["rv"]},
    )
return rows[-1]["rv"]
</code></pre>
<p>(Table and column names are simplified for the post.)</p>
<p>If the connection dies mid-chunk, Postgres rolls back both the partial rows and the checkpoint update. The checkpoint still points at the end of the last complete chunk, so the next run starts exactly there:</p>
<p>with dst.connect() as c:
    last = c.execute(text("SELECT last_rv FROM sync_checkpoint WHERE job = 'sales'")).scalar_one()
while (last := sync_chunk(src, dst, last, CHUNK_SIZE)) is not None:
    pass
Three things to know before you copy this:</p>
<p>Index the rowversion column, or every chunk scans the table.
Adding a rowversion column to a large source table is a schema change that touches every row. Plan it with whoever owns that database.
Deletes are not seen. A deleted row has no version left to read. Use soft deletes, or SQL Server Change Tracking if deletes matter.
4. Make retries harmless with an upsert on source_id
Transactions protect you from half-written chunks. They do not protect you from a retry that re-sends a chunk that actually committed (for example, the commit succeeded but the acknowledgement was lost). The fix is a unique key on source_id and INSERT ... ON CONFLICT (source_id) DO UPDATE. Writing the same chunk twice leaves the table exactly as if it had been written once, so retries can't duplicate. It also makes updates safe: a row that changes after it was copied comes back with a newer rowversion and simply overwrites its old copy.</p>
<ol start="5">
<li>Test it by actually breaking it
I did not trust this until I had broken it on purpose: kill the connection in the middle of a chunk, resume, then compare row counts and checksums between source and target. Then test the other failure: a slow writer that holds a transaction open while newer rows commit. That is exactly how a reader found the bug in the first version of this post. On my portfolio there is an interactive version of this: a simulated sync you can cut mid-chunk and resume, with a duplicates counter that stays at zero.</li>
</ol>
<p>The same idea, one layer up: scores that survive an outage
The CRM layer scores every lead with an LLM (Groq). LLM APIs stall too, so scoring follows the same philosophy as the sync: a failure must degrade, not break. When the model times out, rule-based scoring takes over (for example, "3+ orders in 90 days and a quote accepted within 7 days" means hot) and the screen says that rules, not the model, produced the score. Users always get an answer, and they always know where it came from.</p>
<p>Takeaways
Chunk the work and make each chunk atomic.
Store progress in the same transaction as the data it describes.
On a live source, page by a commit-safe version (rowversion below MIN_ACTIVE_ROWVERSION()), not by id.
Make writes idempotent with a natural key and an upsert, so retries are safe.
Break it on purpose before you trust it.
I'm Sparsh Prajapati, a full-stack engineer at Cloudzent in Gurugram, India. More of my work, including the interactive sync demo: sparshprajapati.com · LinkedIn · GitHub</p>
]]></content:encoded></item><item><title><![CDATA[Proving consent without asking anyone to trust our database]]></title><description><![CDATA[tags: security, cryptography, privacy, typescript India's Digital Personal Data Protection Act (DPDP, 2023) says a company must be able to show that a…]]></description><link>https://sparshprajapati.hashnode.dev/proving-consent-without-asking-anyone-to-trust-our-database</link><guid isPermaLink="true">https://sparshprajapati.hashnode.dev/proving-consent-without-asking-anyone-to-trust-our-database</guid><dc:creator><![CDATA[Sparsh Prajapati]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:44:20 GMT</pubDate><content:encoded><![CDATA[<p>tags: security, cryptography, privacy, typescript</p>
<p>India's Digital Personal Data Protection Act (DPDP, 2023) says a company must be able to show that a person consented before it processed their data. Most consent tools answer that with a database row: <code>visitor 7f3a, analytics = granted, 09:14</code>. The trouble is who can edit that row. Anyone with admin access to the database, including the company being audited, can change it later, and nothing in the row would show it.</p>
<p>I'm the primary developer of PrivacySuraksha, a DPDP compliance platform that is live in production. One of the problems I had to solve was this one: how do you prove a consent record is genuine without asking the auditor to trust our database?</p>
<p>The answer we shipped is a ledger nobody can quietly edit. Every consent event is hashed. Every day, all of that day's hashes are sealed into one SHA-256 Merkle root. The root is signed with Ed25519 and timestamped on Bitcoin with OpenTimestamps. An auditor can then verify any single record without trusting us.</p>
<p>Here is how the pieces fit, and why each one is there.</p>
<h2>1. Hash every event</h2>
<p>A consent event is a small, canonical string: record id, a pseudonymous visitor id, the purpose, the decision and a timestamp.</p>
<pre><code>cs_0142 visitor 1c9e marketing=denied 2026-11-30T09:20Z
</code></pre>
<p>Its SHA-256 hash becomes a leaf of the day's tree. In the browser or on Cloudflare Workers, WebCrypto does this in a few lines:</p>
<pre><code class="language-ts">const enc = new TextEncoder();

async function sha256(data: Uint8Array): Promise&lt;Uint8Array&gt; {
  return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
}

// a 0x00 prefix for leaves and 0x01 for inner nodes (as in RFC 6962), so a leaf can never pass as a node
const leaf = (record: string) =&gt; sha256(new Uint8Array([0, ...enc.encode(record)]));
const node = (l: Uint8Array, r: Uint8Array) =&gt; sha256(new Uint8Array([1, ...l, ...r]));
</code></pre>
<p>Change one character of the record and the hash changes completely. That property is what everything else builds on.</p>
<h2>2. Seal a day into one Merkle root</h2>
<p>Storing thousands of hashes does not help an auditor much on its own. A Merkle tree turns them into a single 32-byte value: hash leaves in pairs, then hash those results in pairs, until one hash is left.</p>
<pre><code class="language-ts">async function merkleRoot(leaves: Uint8Array[]): Promise&lt;Uint8Array&gt; {
  let level = leaves;
  while (level.length &gt; 1) {
    const next: Uint8Array[] = [];
    for (let i = 0; i &lt; level.length; i += 2) {
      const right = level[i + 1] ?? level[i]; // odd count: pair the last node with itself
      next.push(await node(level[i], right));
    }
    level = next;
  }
  return level[0];
}
</code></pre>
<p>If any record from that day is edited, added or removed, the root changes. So instead of protecting every row, we only have to protect one value per day.</p>
<h2>3. Sign the root</h2>
<p>A root on its own proves the data has not changed since the root was computed. It does not say who computed it. Signing the daily root with an Ed25519 key ties it to us: an auditor can check the signature with our public key, and a forged root will not verify.</p>
<h2>4. Anchor it on Bitcoin</h2>
<p>A signature still leaves one gap: we hold the key, so in theory we could rebuild a day's tree with an edited record, sign the new root and backdate it. Timestamping closes that gap. We submit the signed root to OpenTimestamps, which commits it into a Bitcoin transaction. Once that transaction is in a block, anyone can show the root existed at that time, and no one, including us, can change it afterwards without the mismatch showing.</p>
<h2>5. Verify one record without the rest</h2>
<p>An auditor who wants to check one consent does not need the whole day's data. They need the record, the sibling hashes on its path to the root (an inclusion proof, about log2(n) hashes), and the signed, anchored root.</p>
<pre><code class="language-ts">type Step = { hash: Uint8Array; left: boolean };

async function verify(record: string, proof: Step[], root: Uint8Array) {
  let h = await leaf(record);
  for (const s of proof) {
    h = s.left ? await node(s.hash, h) : await node(h, s.hash);
  }
  return h.every((b, i) =&gt; b === root[i]);
}
</code></pre>
<p>If the recomputed root matches the signed, Bitcoin-anchored root, the record is exactly what was there on that day. If one letter changed, it will not match. That is the whole point: the check does not depend on trusting our database, our servers or us.</p>
<h2>What I would tell someone building this</h2>
<ul>
<li><strong>Keep personal data out of the leaves.</strong> Use pseudonymous ids. The ledger proves what happened; it should not become another copy of the personal data you are trying to protect.</li>
<li><strong>Prefix leaves and nodes differently.</strong> Without the 0x00 / 0x01 prefixes, an attacker can present an inner node as if it were a leaf. It is a one-byte fix.</li>
<li><strong>Make the record format canonical.</strong> If two services serialise the same event differently, their hashes differ and proofs fail. Pick one exact format and test it.</li>
<li><strong>Batch, then anchor.</strong> One root per day keeps signing and anchoring cheap no matter how many events there are.</li>
<li><strong>Show the failure.</strong> On my portfolio, the hero is a live Merkle tree: change one letter of a consent record and you can watch the proof fail. It explains the idea faster than any diagram.</li>
</ul>
<p>You can try that demo at <a href="https://sparshprajapati.com">sparshprajapati.com</a>.</p>
<hr />
<p><em>I'm Sparsh Prajapati, a full-stack engineer at Cloudzent in Gurugram, India. I build product interfaces and the systems underneath them. More of my work: <a href="https://sparshprajapati.com">sparshprajapati.com</a> · <a href="https://www.linkedin.com/in/prajapatisparsh/">LinkedIn</a> · <a href="https://github.com/prajapatisparsh">GitHub</a></em></p>
]]></content:encoded></item></channel></rss>