<?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 Somak Dutta on Medium]]></title>
        <description><![CDATA[Stories by Somak Dutta on Medium]]></description>
        <link>https://medium.com/@somaktukai?source=rss-58a940293646------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TecBhGgEchW3ImdvAv40EA.jpeg</url>
            <title>Stories by Somak Dutta on Medium</title>
            <link>https://medium.com/@somaktukai?source=rss-58a940293646------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:44:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somaktukai/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[How I reduced 90% memory by avoiding in loop defer]]></title>
            <link>https://blog.stackademic.com/how-i-reduced-90-memory-by-avoiding-in-loop-defer-bf423974b448?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf423974b448</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[profiling]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 11:49:35 GMT</pubDate>
            <atom:updated>2026-11-16T11:55:10.936Z</atom:updated>
            <content:encoded><![CDATA[<p>Story of how go profiling and simple defer tricks can help you reduce memory footprint for massive customer inputs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfZwMqNNs2vPXelzrtLRBg.png" /><figcaption>image courtesy : Gemini</figcaption></figure><h4>Origin Story</h4><p>I was working with a lot of zip files for a customer POC for newly developed SCA feature. Customer was very interested in trying out the “worst-in-line” cases and wanted me to successfully scan a 200gb zip file ( <em>I am not kidding! ) .</em></p><p>I cant remember the exact number of files within the zip, but fair to say it was beyond 2000 files. Quickly evident was how bad memory readings were for the scan in question and via profiling I pin pointed the problem to lo and behold our unzip.go piece of code. <em>But it wasnt where you would think.</em></p><p>This short piece will tell you 3 things:</p><ol><li>original issue and metrics observed</li><li>how to solve it cleanly</li><li>lots of love to end</li></ol><h4>Issue</h4><p>A typical golang code for unzip looks like so</p><pre>type nopReadFrom struct{ io.Writer }<br><br>func Unzip_Bad(source string, destination string, filterFunc func(name string) bool) error {<br> source = filepath.Clean(source)<br> if _, err := os.Stat(source); err != nil &amp;&amp; errors.Is(err, os.ErrNotExist) {<br>  return fmt.Errorf(&quot;unable to unzip non existent file: %s&quot;, source)<br> } else if err != nil {<br>  return fmt.Errorf(&quot;unable to unzip invalid file: %s&quot;, source)<br> }<br><br> destination = filepath.Clean(destination)<br> fileI, err := os.Stat(destination)<br> if err != nil &amp;&amp; errors.Is(err, os.ErrNotExist) {<br>  if err := os.MkdirAll(destination, 0755); err != nil {<br>   return fmt.Errorf(&quot;unable to unzip, cannot create destination directory: %s&quot;, destination)<br>  }<br> } else if err != nil {<br>  return fmt.Errorf(&quot;unable to unzip, cannot access destination: %s&quot;, destination)<br> } else if !fileI.IsDir() {<br>  return fmt.Errorf(&quot;unable to unzip, target destination is a file: %s&quot;, destination)<br> }<br><br> archive, err := zip.OpenReader(source)<br> if err != nil {<br>  return err<br> }<br> defer archive.Close()<br><br> // Pre-allocate one copy buffer shared across all files in the archive.<br> copyBuf := make([]byte, 32&lt;&lt;10)<br> // Pre-compute destination prefix for zip-slip checks (avoids alloc per file).<br> destPrefix := destination + string(filepath.Separator)<br><br> for _, file := range archive.Reader.File {<br><br>  if filterFunc != nil &amp;&amp; filterFunc(file.Name) {<br>   continue<br>  }<br><br>  // Zip-slip protection: reject paths that escape the destination root.<br>  path := filepath.Join(destination, file.Name)<br>  if path != destination &amp;&amp; !strings.HasPrefix(path, destPrefix) {<br>   return fmt.Errorf(&quot;zip slip: illegal path in archive: %s&quot;, file.Name)<br>  }<br><br>  if file.FileInfo().IsDir() {<br>   if err := os.MkdirAll(path, 0755); err != nil {<br>    return err<br>   }<br>   continue<br>  }<br><br>  // Ensure parent directories exist for files with nested paths.<br>  if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {<br>   return err<br>  }<br><br>  reader, err := file.Open()<br>  if err != nil {<br>   return err<br>  }<br>  defer reader.Close()<br><br>  writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())<br>  if err != nil {<br>   return err<br>  }<br>  defer func() {<br>   if cerr := writer.Close(); err == nil {<br>    err = cerr<br>   }<br>  }()<br>  _, err = io.CopyBuffer(nopReadFrom{writer}, reader, copyBuf)<br>  if err != nil {<br>   return err<br>  }<br><br> }<br> return nil<br>}</pre><p>The above code is quite typical, lookup “how to unzip in golang” will probably provide you with the above code. Yes ignore the optimization in providing a copy buffer and zip slip fixes.</p><p>Now for most small zip files, or even massive zip files with very little inner files the above code is perfectly fine. However the moment you come across a file with hundreds/thousands of inner files, you will quick find memory foot print increasing ( in_use memory) — you wont notice saw tooth figures in your monitoring dashboards, you will find flat large memory plateaus or worse encounter out of memory issues.</p><p>Something like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eW5tZ56WTH645QLenZrXTQ.png" /><figcaption>Large blocks of memory in use stats</figcaption></figure><p>If you have read the code above, you have probably already pinpointed the issue.</p><p>Issue : the defer in for loops</p><ul><li>defer waits for function to return , not for the inner for loop : the reader.Close() for n number of files within a zip does not fire till the function unzip returns</li><li>the above causes a memory pile up, because the close function hands back the flatereader to the pool to archive/zip for reuse. If that doesnt happen it would mean every entry for every file within the zip file gets a new.</li></ul><p>A simple profiler tool such as Parca ( boy i loveee parca <a href="https://github.com/parca-dev/parca">https://github.com/parca-dev/parca</a>) will tell you the problem immediately , see below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImDWo0-VaZSlyXkfPShwrA.png" /></figure><h4>Solution</h4><p>Well we know what the problem is : defer in loops.</p><p>So we know what the solution is : move defer out of loops, ensure close executes within loop every time.</p><p>There are two way to do this:</p><ol><li>Remove the defer reader.Close() and replace with reader.Close() and writer.Close()</li><li>but i do kinda like using defer, its go idiomatic and familiar. So whats a neat trick we can use — inline closure.</li></ol><p>The code looks like so , <em>pay special attention to the very next line after the for loop</em></p><pre>type nopReadFrom struct{ io.Writer }<br><br>func Unzip(source string, destination string, filterFunc func(name string) bool) error {<br> source = filepath.Clean(source)<br> if _, err := os.Stat(source); err != nil &amp;&amp; errors.Is(err, os.ErrNotExist) {<br>  return fmt.Errorf(&quot;unable to unzip non existent file: %s&quot;, source)<br> } else if err != nil {<br>  return fmt.Errorf(&quot;unable to unzip invalid file: %s&quot;, source)<br> }<br><br> destination = filepath.Clean(destination)<br> fileI, err := os.Stat(destination)<br> if err != nil &amp;&amp; errors.Is(err, os.ErrNotExist) {<br>  if err := os.MkdirAll(destination, 0755); err != nil {<br>   return fmt.Errorf(&quot;unable to unzip, cannot create destination directory: %s&quot;, destination)<br>  }<br> } else if err != nil {<br>  return fmt.Errorf(&quot;unable to unzip, cannot access destination: %s&quot;, destination)<br> } else if !fileI.IsDir() {<br>  return fmt.Errorf(&quot;unable to unzip, target destination is a file: %s&quot;, destination)<br> }<br><br> archive, err := zip.OpenReader(source)<br> if err != nil {<br>  return err<br> }<br> defer archive.Close()<br><br> // Pre-allocate one copy buffer shared across all files in the archive.<br> copyBuf := make([]byte, 32&lt;&lt;10)<br> // Pre-compute destination prefix for zip-slip checks (avoids alloc per file).<br> destPrefix := destination + string(filepath.Separator)<br><br> for _, file := range archive.Reader.File {<br><br>  f := func() error {<br>   if filterFunc != nil &amp;&amp; filterFunc(file.Name) {<br>    return nil<br>   }<br><br>   // Zip-slip protection: reject paths that escape the destination root.<br>   path := filepath.Join(destination, file.Name)<br>   if path != destination &amp;&amp; !strings.HasPrefix(path, destPrefix) {<br>    return fmt.Errorf(&quot;zip slip: illegal path in archive: %s&quot;, file.Name)<br>   }<br><br>   if file.FileInfo().IsDir() {<br>    if err := os.MkdirAll(path, 0755); err != nil {<br>     return err<br>    }<br>    return nil<br>   }<br><br>   // Ensure parent directories exist for files with nested paths.<br>   if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {<br>    return err<br>   }<br><br>   reader, err := file.Open()<br>   if err != nil {<br>    return err<br>   }<br>   defer reader.Close()<br><br>   writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())<br>   if err != nil {<br>    return err<br>   }<br>   defer func() {<br>    if cerr := writer.Close(); err == nil {<br>     err = cerr<br>    }<br>   }()<br>   _, err = io.CopyBuffer(nopReadFrom{writer}, reader, copyBuf)<br>   if err != nil {<br>    return err<br>   }<br>   return nil<br>  }<br>  if err := f(); err != nil {<br>   return err<br>  }<br><br> }<br> return nil<br>}</pre><p>And et voila, thats it folks. Thats all there is to it.</p><p>I loveeeee when damaging issues can be fixed by mere simple code and i love it more when those come as a consequence of profiling.</p><p>I thank you for reading so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*gazH4B3TRxlGvhOO.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf423974b448" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-i-reduced-90-memory-by-avoiding-in-loop-defer-bf423974b448">How I reduced 90% memory by avoiding in loop defer</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a structural fingerprinting tool found a potential DoS in nats-server that no SAST rule would…]]></title>
            <link>https://medium.com/@somaktukai/how-a-structural-fingerprinting-tool-found-a-potential-dos-in-nats-server-that-no-sast-rule-would-b201a3f2b499?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/b201a3f2b499</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 04:53:55 GMT</pubDate>
            <atom:updated>2026-08-09T04:53:55.744Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How a structural fingerprinting tool found a potential DoS in nats-server that no SAST rule would ever flag — and what happened when I reported it</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Lcg7GOvpslVOMx4KmpW9Q.jpeg" /><figcaption>Image courtesy nano banana</figcaption></figure><p>I promised in my first <a href="https://medium.com/faun/structural-fingerprint-for-golang-repositories-a-case-study-ae560bafec84">blog</a> about <a href="https://github.com/somak2kai/beats">beats</a> , there has to be a security intelligence aspect to finding structural fingerprint and their outliers for a codebase.</p><p>This post will talk you through how it “potentially” found a DoS report for nats-server. <strong><em>To be upfront at the outset, the issue was dismissed by the security team by Nats</em></strong>. And i have reported their response verbatim below. But lets start at the start.</p><p>Beats now supports finding security flaws/issues in code — as a tool beats clusters structurally similar functions, flags outlier functions missing or adding steps their peers have, then an LLM maps those gaps to CWE classes and scans clusters for shared insecure conventions. A few weeks ago I ran beats against the <a href="https://github.com/nats-io/nats-server">nats-server</a> codebase. TBh I wasn’t hunting for anything specific. NATS had a professional <a href="https://github.com/trailofbits/publications/blob/master/reviews/2025-04-ostif-nats-securityreview.pdf">third-party audit</a> (Trail of Bits, 2025). I did not expect to find anything.</p><p>Beats found something anyway.</p><h4><strong>What beats actually does</strong></h4><p>Most SAST analyzers work against known patterns such sql query concatenation, trusting unauthorized inputs or other known catalogue of bad patterns. Analyzers would walk your code looking for matches. That is powerful for the bugs someone already thought to write a rule for. It’s blind to everything else.</p><p>Beats does something different and is intentionally much dumber. It doesn’t know what a vulnerability is or what a flaw is. It parses every function in a Go/Java repository into a structural fingerprint — its control-flow shape, the sequence of operations and then clusters functions that have the same shape, regardless of what they’re named or what package they live in. Then for each cluster it reports the odd one out eg the function that has five of the six steps its siblings have, and is quietly missing the sixth.</p><p>That’s it. No CWE list, no taint rules, no notion of a dangerous sink. Just: hey these n functions look identical, why does this one skip a step the other six take?</p><h4>Heres the dismissed issue in nats-server</h4><p>Ok enough talk, lets get into some piece of code.</p><p>Issue reported : The client/leaf publish parsers (processPub, processHeaderPub,processLeafMsgArgs, processLeafHeaderMsgArgs) enforce max_payload before trusting a declared message size. The three routeparsers processRoutedMsgArgs, processRoutedHeaderMsgArgs,processRoutedOriginClusterMsgArgs do not.</p><p>A single line like “RMSG ACC foo 999999999\r\n” forces a ~953 MiB heap allocation before any payload bytes arrive. The attacker never needs to send the actual payload. Repeated across connections, this causes OOM and crashes the cluster member.</p><p>In nats-server message-parsing code is a family of functions whose entire job is to read the argument line of an incoming message eg <strong><em>PUB foo 128\r\</em></strong><em> </em>and pull the subject, reply-to, and declared payload size out of it.</p><p>Beats clustered all seven together — correctly, they’re structurally near-identical — and flagged that three of them were missing a step the other four had. That step is the `max_payload` check</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zWI3lpDtyLI5MR_ASBuKw.png" /><figcaption>Image courtesy nano banana</figcaption></figure><p>A full reproducible test was provided when reporting the issue along with a potential patch.</p><h4>When i reported it</h4><p>I want to be honest about the caveats, because I put them in the report myself. This is not a client-facing, unauthenticated, drive-by vulnerability. To exploit it, you need to already be able to speak the router or gateway wire protocol to a cluster member, specifically meaning you’re a cluster peer, a compromised one, or you’ve landed on a route/gateway listener that’s reachable without real authentication. That’s a meaningfully higher bar than hitting a public client port.</p><p>But it’s not nothing, either. Gateways specifically exist to connect <em>independently administered</em> supercluster . The whole point is that a peer operated by one team can talk to servers operated by another. A missing bound in that path means one misbehaving or compromised org can OOM a cluster it doesn’t otherwise control.</p><p>Heres the response from nats security team:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR-EZfOssZ8LjRdywxVh7w.png" /></figure><p>That’s a fair call, and I don’t disagree with it. They also explicitly said it’s not embargoed, which is why I can write this at all</p><h4><strong>What I’m taking from this</strong></h4><p>I dont write these articles to publicize a tool that i built. I write these articles as i like record keeping of what happened and what did not happen. Something for posterity, even if i am the sole reader. ( which is mostly true :P )</p><p>The finding held up technically — the asymmetry is real, the patch is real, the PoC reproduces cleanly. What didn’t hold up was my initial severity read, because I was reasoning about the code shape without fully pricing in <em>who</em> gets to be on the sending end of that connection. That’s a useful humbling: a tool that finds real structural asymmetries still hands you a hypothesis, not a verdict.</p><p>I still think structurally-driven fingerprinting is a technique I would point at any codebase with enough repeated patterns to make it worth trying. It won’t find you a SQL injection. It is very good at finding the one function in a family of seven that quietly stopped doing what its siblings do. As it turns out, those are a category of bug that’s been sitting in plain sight, in plainly correct looking code, the whole time.</p><p>I thank you for reading so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*-2imQcfP2jAjwP_Y.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b201a3f2b499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The K8S Cron Job Bug present for ~5years and how structural fingerprint found it]]></title>
            <link>https://blog.stackademic.com/the-backoff-that-outlived-its-cause-174ffd51026e?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/174ffd51026e</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[source-code-analysis]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 04:49:43 GMT</pubDate>
            <atom:updated>2026-11-16T11:56:03.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>How beats uncovered Rate Limit Back Off issue in Kubernetes CronJob controller</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHAtlVMIQeHLVQ8jfMnNTQ.png" /></figure><p>I have been building <a href="https://github.com/somak2kai/beats">beats</a> and lol, talking about it a lot. I pointed beats at <a href="https://github.com/kubernetes/kubernetes">kubernetes</a> to see and verify the structural fingerprint it identifies and potential outliers. Lets uncover in this article how it was uncovered, what was the issue and what was the fix.</p><p>For the impatient ones out there here are the links</p><ul><li>Issue: <a href="https://github.com/kubernetes/kubernetes/issues/139917">https://github.com/kubernetes/kubernetes/issues/139917</a></li><li>PR: <a href="https://github.com/kubernetes/kubernetes/pull/139918">https://github.com/kubernetes/kubernetes/pull/139918</a></li></ul><h3>What Beats uncovered</h3><p>When i pointed beats at Kubernetes codebase, it uncovered 10 outliers for a cluster of around ~160. However only 2 were considered to be something thats needed attention and 1 particularly stood out.</p><pre>cronjob/processNextWorkItem (pkg/controller/cronjob/cronjob_controllerv2.go:192) — pattern: b311c1338528ba34<br>Signal: token delta: +CASE +SWITCH vs peers; peer body comparison: all 5 cluster peers call queue.Forget(key) unconditionally on the success path before returning true. In this function, Forget is only called inside case requeueAfter != nil. When err == nil &amp;&amp; requeueAfter == nil (clean sync, no reschedule), neither case fires and Forget is never called.<br>Concern: The success path omits queue.Forget(key), so the rate limiter entry for a successfully synced key is never reset if no re-queue is needed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glwt7PVi5OFpQsZWfbG4sA.png" /></figure><p>Fair warning up front: this is not a dramatic bug. Nobody’s cluster is on fire because of it. However it’s a perfect little specimen of a <em>silent</em> bug, and chasing it down end to end was a lot of fun.</p><h3>A 60-second primer</h3><p>A Kubernetes controller is a loop. It watches some kind of object, compares the world as it is to the world as the spec says it should be and nudges reality toward the spec. For a CronJob, that means: is it time to run? If so, create a Job. Then check again later.</p><p>The two pieces that matter for this story are :</p><ul><li><strong>workqueue:</strong> cronjob_controllerv2 don’t process objects directly off the network; they push <em>keys</em> (namespace/cron_name strings) onto an in-memory <a href="https://pkg.go.dev/k8s.io/client-go/util/workqueue">queue</a> and worker go routines pull keys off and reconcile them one at a time.</li><li><strong>rate limiter: </strong>cronjob_controllerv2 also calls apis to create <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/cronjob/cronjob_controllerv2.go#L631">jobs</a> ( among other things) . Say something fails here you don’t want to retry in a tight loop and hammer an already-sick API server. So the queue has an exponential backoff. Each consecutive failure for a key doubles the delay before its next retry with maximum delay capped at about 16 minutes. The mechanism is a little counter per key. AddRateLimited(key) bumps the counter and schedules a delayed retry. Forget(key) deletes the counter (essentially backoff reset /decremented)</li></ul><p>Now what beats uncovered was right here : the entire bug lives in when Forget does and doesn&#39;t get called.</p><h4>A counter with an “up” but no “down”</h4><p>Here’s the heart of the controller’s work loop, lightly trimmed (pkg/controller/cronjob/cronjob_controllerv2.go#processNextWorkItem):</p><pre>requeueAfter, err := jm.sync(ctx, key)<br>switch {<br>case err != nil:<br>    jm.queue.AddRateLimited(key)            // failed: back off and retry<br>case requeueAfter != nil:<br>    jm.queue.Forget(key)                    // success: reset backoff…<br>    jm.queue.AddAfter(key, *requeueAfter)   // …and check again later<br>}</pre><p>The code handles two specific cases. Either the sync errored (back off), or it succeeded and asked to be revisited at a specific time (reset the counter, requeue).</p><p>However sync() doesn&#39;t return only two outcomes, it returns a third. Its signature is (*time.Duration, error) and there&#39;s a third combination the switch never names: (nil, nil)<em>nEssentially no error, and no re queue requested.</em></p><p>I took one example flow, say :<br>Lets take a suspended CronJob: on any given sync it may or may not need a status write, and that write may or may not succeed.( in pkg/controller/cronjob/cronjob_controllerv2.go#syncCronJob )</p><ul><li>Status write fails → sync returns (nil, err) → processNextWorkItem takes the err != nil branch → AddRateLimited <strong>increments</strong> the failure count.</li><li>Status write succeeds → sync returns (nil, nil) → no branch runs → the <strong>count is left unchanged</strong>.</li></ul><p>So the very same code path can push the counter up but never pulls it back down. It has an up but no down. Over a rough patch, a CronJob’s backoff count can ratchet upward and simply never reset . This is because the only thing that <em>would</em> reset it, Forget on the clean success path, isn&#39;t being called.</p><p>So the picture is: a real, monotonic state leak. Real, but minor.</p><p>But why minor ? It’s <em>minor because the system is mostly self-correcting around it,</em> not because the leak isn’t there. Lets take another example</p><p>Lets walk the dangerous sequence one step further (suspended cron job is just an example that i am taking here).</p><ul><li>A suspended CronJob with a stale counter gets resumed.</li><li>Its next reconcile runs as an <em>active</em> CronJob, and if that reconcile <strong>succeeds</strong>, it returns a real requeueAfter — which lands in the case requeueAfter != nil branch, which calls Forget. The stale counter is wiped right there.</li><li>For the bug to actually delay anything, that first post-resume reconcile has to <em>fail. </em>Because in that case you need the resume to happen while the API is still flaky. If the incident is over by the time you resume, the very first healthy sync cleans up the mess for you.</li></ul><p>Its important for me to point out the above, because i dont want to oversell the issue that was unearthed. To reiterate , Real, but minor.</p><p>But i dont want to undersell the issue either, the next section covers a bit of it. And if you have built/managed systems at your job, it would be interesting.</p><h3>The quietest kind of bug</h3><p>If I had to name the lesson in one line: a bug’s severity isn’t just how bad the effect is, it’s how hard the effect is to <em>attribute</em>. And by that I mean, how do we even unearth a real reason or rootcause when a cronjob is getting delayed by some time. Is it a problem with load on the cluster, is the cluster unhealthy , are the crons specs incorrect, or is it that due to a code issue an earlier stale backoff counter is still over 0. Which in turn contributes to the delay.</p><p>When beats first flagged this, I wanted to lead with the scary number: a CronJob could end up delayed by the full 16-minute backoff cap. That&#39;s technically reachable, and it&#39;s also the wrong thing to emphasize. The genuinely interesting property isn&#39;t the size of the delay. It&#39;s that <strong>the stale backoff state behind it is effectively invisible.</strong> The symptom is observable; its cause is not.</p><p>Think about what happens when the bug actually bites. A CronJob accumulated some backoff during an API hiccup, got suspended (which carries the stale counter forward), and was later resumed . And the first reconcile after resume hits a transient error. Now its retry is delayed using a failure count left over from an incident that’s already over. The Job that should have been created fires late.</p><p>The <em>symptom</em> is observable — a late Job, a CronJob slow to resume, maybe some reconcile churn in the logs. What’s missing is anything connecting that symptom to its cause.</p><p>The cause is an integer that wasn’t reset when the CronJob was suspended last week, and nothing on the cluster points at it</p><h3>What I actually took away</h3><p>The point is the shape of the work. Beats flagged a code smell.After understanding the potential outliers that beats uncovered, one definitely stood out ( also psst.. i have worked on cron before so there was a natural curiosity here). And then came the patience to trace Forget through the codebase of cronjob_controllerv2 and its cousins methods ( that beats showed as well) until I could say, with evidence, exactly when it fired and when it didn&#39;t, and exactly how much that mattered.</p><p>I went in wanting to understand a bug. I came out understanding the workqueue, the rate limiter, the reconcile loop. The bug was the excuse. The understanding was the prize .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*HYj2eRY6LuwDeomi.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174ffd51026e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-backoff-that-outlived-its-cause-174ffd51026e">The K8S Cron Job Bug present for ~5years and how structural fingerprint found it</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro-Benchmarking Java with JMH and Bazel]]></title>
            <link>https://blog.stackademic.com/micro-benchmarking-java-with-jmh-and-bazel-cdf74dc714f6?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdf74dc714f6</guid>
            <category><![CDATA[performance-management]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[bazel]]></category>
            <category><![CDATA[jmh]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 02:45:16 GMT</pubDate>
            <atom:updated>2026-08-14T06:35:20.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcAXPNiMe-CClzoQehzWgQ.png" /></figure><p><em>Ooooh do i love benchmarking </em>.. one of my favourite things to do at work. ( i could go on and on about parca but something else for today…)</p><p>You may have run into this issue while using JMH for your benchmarking needs while using bazel. In which case, you would find this interesting or at the least helpful.</p><p>All code examples are available here <a href="https://github.com/somak2kai/bazel-java-profile">https://github.com/somak2kai/bazel-java-profile</a></p><p>Performance engineering in Java almost always starts with JMH — the Java Microbenchmark Harness, built by the same team that ships the JVM. It is the tool the JDK itself uses for regression testing. It handles warm-up, dead-code elimination, JIT interference, and statistical reporting with an unmatched rigour. If you are using Maven or Gradle, JMH works out of the box: a plugin takes care of everything under the hood.</p><p>Switch to Bazel — which is increasingly common in monorepo shops, large-scale Java and Android codebases, and organisations that need true hermetic, reproducible builds — and you immediately hit a wall:</p><pre>ERROR: Unable to find the resource: /META-INF/BenchmarkList</pre><p>The benchmark runner starts, finds nothing to execute, and exits. No error from javac. No warning at build time. The binary builds cleanly, and then fails at runtime in the most confusing way possible.</p><p>This article explains exactly why that happens, what JMH is actually doing at compile time, and how Bazel’s java_plugin rule is the correct fix.</p><h3>How JMH Works Internally</h3><p>Before debugging the Bazel failure it is worth understanding what JMH does at compile time.</p><p>JMH uses the <strong>Java Annotation Processing Tool (APT)</strong> — the same mechanism behind Lombok, Dagger, AutoValue, and MapStruct. When you annotate a method with @Benchmark, JMH&#39;s annotation processor (BenchmarkProcessor) fires during the javac compilation phase and generates two things:</p><ol><li><strong>Synthetic benchmark runner classes</strong> — for each @Benchmark method, the processor generates a companion class that wires in blackholes, state management, timing infrastructure, and forking logic. These are emitted as .java source files and then compiled as part of the same build.</li><li><strong>META-INF/BenchmarkList</strong> — a plain text resource file that catalogs every discovered benchmark class. When org.openjdk.jmh.Main starts, the very first thing it does is <a href="https://github.com/openjdk/jmh/blob/master/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkList.java#L43">open</a> this file from the classpath.</li></ol><p>If META-INF/BenchmarkList is absent, the runner throws immediately. It has no fallback, no classpath scan, no reflection-based discovery. The resource file is the only source of truth. This is by design.</p><h3>Why Maven and Gradle Don’t Have This Problem</h3><p>The jmh-maven-plugin and the me.champeau.jmh Gradle plugin both configure their respective build tools to run annotation processing as a standard compilation step. When you declare:</p><pre>&lt;!-- Maven pom.xml --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.openjdk.jmh&lt;/groupId&gt;<br>    &lt;artifactId&gt;jmh-generator-annprocess&lt;/artifactId&gt;<br>    &lt;version&gt;1.37&lt;/version&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Maven’s compiler plugin sees a JAR on the annotation processor path that contains — META-INF/services/javax.annotation.processing.Processor with the value org.openjdk.jmh.generators.BenchmarkProcessor. The JDK&#39;s service loader mechanism auto-discovers this processor and runs it automatically during compilation. META-INF/BenchmarkList lands in target/classes and gets packaged into the final JAR or uber-JAR without any extra configuration.</p><p>Gradle works the same way through its annotationProcessor configuration scope. Both tools lean on the JDK’s built-in processor auto-discovery via javax.annotation.processing.Processor service files. This has been standard Java behaviour since Java 6.</p><h3>The Bazel Model</h3><p>Bazel’s Java rules do not use service-file-based processor auto-discovery, and this is intentional.</p><p>In Bazel’s hermetic model, every build action must declare its inputs and outputs explicitly so that the action graph can be cached and replayed with byte-for-byte reproducibility. Silently loading a processor because a JAR happens to contain a META-INF/services file would make the compilation action&#39;s behaviour depend on the implicit contents of dependency JARs — exactly the kind of implicit, order-sensitive behaviour that Bazel is designed to eliminate.</p><p>So when you write:</p><pre># BUILD.bazel — the broken approach<br>java_binary(<br>    name = &quot;jmh_harness_broken&quot;,<br>    srcs = glob([&quot;src/main/java/**/*.java&quot;]),<br>    main_class = &quot;org.openjdk.jmh.Main&quot;,<br>    deps = [<br>        &quot;@maven//:org_openjdk_jmh_jmh_core&quot;,<br>        &quot;@maven//:org_openjdk_jmh_jmh_generator_annprocess&quot;,<br>    ],<br>)</pre><p>Bazel compiles the Java source using javac, but it passes the JMH JARs purely as compile-time classpath entries, not as annotation processors. The jmh-generator-annprocess JAR is there for symbol resolution — so @Benchmark, @State, and friends resolve without errors — but BenchmarkProcessor is never invoked.</p><p>The binary is built. The @Benchmark annotations remain as inert metadata. META-INF/BenchmarkList is never written. And you end up with an error that looks like</p><pre>Exception in thread &quot;main&quot; java.lang.RuntimeException: ERROR: Unable to find the resource: /META-INF/BenchmarkList<br>        at org.openjdk.jmh.runner.AbstractResourceReader.getReaders(AbstractResourceReader.java:98)<br>        at org.openjdk.jmh.runner.BenchmarkList.find(BenchmarkList.java:124)<br>        at org.openjdk.jmh.runner.Runner.internalRun(Runner.java:252)<br>        at org.openjdk.jmh.runner.Runner.run(Runner.java:208)<br>        at org.openjdk.jmh.Main.main(Main.java:71)</pre><h3>The Fix: java_plugin</h3><p>Bazel provides a first-class rule for this purpose: java_plugin. It wraps an annotation processor JAR and gives the build system everything it needs to invoke the processor explicitly during compilation:</p><pre>java_plugin(<br>    name = &quot;jmh_annotation_processor&quot;,<br>    processor_class = &quot;org.openjdk.jmh.generators.BenchmarkProcessor&quot;,<br>    deps = [<br>        &quot;@maven//:org_openjdk_jmh_jmh_generator_annprocess&quot;,<br>        &quot;@maven//:org_openjdk_jmh_jmh_core&quot;,<br>    ],<br>)</pre><p>The processor_class attribute is the fully-qualified name of the class that implements javax.annotation.processing.Processor. Bazel passes this to javac via -processor org.openjdk.jmh.generators.BenchmarkProcessor, making the invocation explicit rather than auto-discovered.</p><p>With the plugin declared, you compile the benchmark sources through a java_library that references the plugin:</p><pre>java_library(<br>    name = &quot;benchmark_lib&quot;,<br>    srcs = glob([&quot;src/main/java/**/*.java&quot;]),<br>    plugins = [&quot;:jmh_annotation_processor&quot;],    # &lt;-- APT runs here<br>    deps = [<br>        &quot;@maven//:org_openjdk_jmh_jmh_core&quot;,<br>        &quot;@maven//:org_openjdk_jmh_jmh_generator_annprocess&quot;,<br>    ],<br>)</pre><p>During this compilation step, BenchmarkProcessor scans every @Benchmark-annotated method, generates the synthetic runner classes, and writes META-INF/BenchmarkList into benchmark_lib.jar. The resource file now exists.</p><p>Finally, the binary just wires together the library and its runtime dependencies — no srcs needed here because all compilation happened in benchmark_lib:</p><pre>java_binary(<br>    name = &quot;jmh_harness&quot;,<br>    main_class = &quot;org.openjdk.jmh.Main&quot;,<br>    runtime_deps = [<br>        &quot;:benchmark_lib&quot;,<br>        &quot;@maven//:org_openjdk_jmh_jmh_core&quot;,<br>        &quot;@maven//:net_sf_jopt_simple_jopt_simple&quot;,<br>        &quot;@maven//:org_apache_commons_commons_math3&quot;,<br>    ],<br>)</pre><p>java_library is where compilation happens — and therefore where the annotation processor must run to write BenchmarkList. java_binary just links the result. Separating them makes the intent explicit and lets other rules reuse :benchmark_lib without re-triggering compilation.</p><h3>Summary</h3><p>The META-INF/BenchmarkList error is not a JMH bug, a Bazel bug, or a configuration mistake in the traditional sense. It is a consequence of Bazel&#39;s explicit-by-design compilation model meeting JMH&#39;s compile-time code generation.</p><p>But its easy to solve for the same. For an easy demonstration :</p><ol><li>clone <a href="https://github.com/somak2kai/bazel-java-profile">https://github.com/somak2kai/bazel-java-profile</a></li><li>run bazel run //:jmh_harness_broken to check the broken flow</li><li>run bazel run //:jmh_harness for the flow that works.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*A6icznbfr6y0yVuw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdf74dc714f6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/micro-benchmarking-java-with-jmh-and-bazel-cdf74dc714f6">Micro-Benchmarking Java with JMH and Bazel</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Baking a Version String into a GraalVM Native Image]]></title>
            <link>https://blog.stackademic.com/baking-a-version-string-into-a-graalvm-native-image-40b1535c57d6?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b1535c57d6</guid>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 05:43:31 GMT</pubDate>
            <atom:updated>2026-08-07T07:25:55.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCV3Plx7PAD0pIMNharVEA.png" /></figure><h3>How I Got Here</h3><p>I was building <a href="https://github.com/somak2kai/jbeats">jbeats</a> — a Java CLI tool that parses Java source files and emits per-method metadata as JSON. I distribute jbeats as a GraalVM native binary via Homebrew.</p><p>I tagged a release, the CI built the native images, Homebrew picked them up. Everything looked fine:</p><pre>$ brew upgrade jbeats<br>==&gt; Upgrading somak2kai/tap/jbeats<br>  0.1.2 -&gt; 0.1.4<br>🍺  /opt/homebrew/Cellar/jbeats/0.1.4: 3 files, 20.5MB, built in 3 seconds</pre><p>Then I ran:</p><pre>$ jbeats --version<br>jbeats 0.1.0</pre><p>No no no not 0.1.0 :O :(</p><p>The version I had hardcoded in Main.java on day one. Homebrew correctly installed 0.1.4. The binary reported 0.1.0. Something was clearly wrong.</p><p>The first fix seemed obvious — pass the version from the git tag at build time:</p><pre>mvn -Pnative package -DskipTests -Djbeats.version=v0.1.4</pre><p>And read it back:</p><pre>$ jbeats --version<br>jbeats dev</pre><p>The fallback dev was being printed .. me sad again :( The property had vanished entirely.</p><p>That’s when I understood what GraalVM native-image actually does — and why -D properties don&#39;t behave the way you expect.</p><h3>The Problem</h3><p>You’re building a CLI tool in Java. You compile it to a native binary with GraalVM’s native-image. You want mytool --version to print the version from your release tag — say, v1.2.0.</p><p>The obvious thing to try:</p><pre>native-image -Dapp.version=1.2.0 -jar myapp.jar</pre><p>Then in code:</p><pre>System.out.println(System.getProperty(&quot;app.version&quot;, &quot;dev&quot;));</pre><p>You build. You run. It prints dev.</p><p>The property evaporated. Here’s why.</p><p>GraalVM native-image is not a JIT compiler. It performs <strong>Ahead-of-Time (AOT) compilation</strong> — it runs a static analysis of your entire program, determines what code paths are reachable, and compiles everything down to a standalone binary. No JVM at runtime.</p><p>System properties passed with -D during the native-image build are <strong>build-time properties</strong>. They influence the analysis phase — things like logging configuration, feature flags, and framework bootstrapping during compilation. They are not automatically carried into the final binary as runtime state.</p><p>The answer is --initialize-at-build-time.</p><h3>How Class Initialization Works in Native Image</h3><p>In a standard JVM, classes are initialized lazily — the first time they are accessed at runtime. Their static initializers (static {} blocks and static field assignments) run then.</p><p>GraalVM native-image gives you control over this. You can tell it to initialize specific classes <strong>during the build</strong> instead. When it does, static fields get their values computed and <strong>baked into the binary as constants</strong>. At runtime, those classes are already initialized — no work to do, no properties to look up.</p><p>This is the lever we need.</p><h3>The Fix</h3><p>Create a dedicated class whose sole job is to hold the version string:</p><pre>package com.example;<br><br>/**<br> * Initialized at native-image build time.<br> * The VERSION field is resolved during compilation and baked<br> * into the binary — no runtime property lookup needed.<br> */<br>public final class Version {<br>    public static final String VALUE =<br>        System.getProperty(&quot;app.version&quot;, &quot;dev&quot;);<br><br>    private Version() {}<br>}</pre><p>Tell GraalVM to initialize it at build time. In your native-image arguments (or Maven pom.xml):</p><pre>--initialize-at-build-time=com.example.Version</pre><p>Now the flow is:</p><ol><li>native-image starts, initializes Version during build</li><li>System.getProperty(&quot;app.version&quot;, &quot;dev&quot;) runs <strong>at compile time</strong> — reads v1.2.0 from the build environment</li><li>&quot;v1.2.0&quot; is stored in the static field and baked into the binary</li><li>At runtime, Version.VALUE is just a constant — no JVM, no property lookup, no fallback</li></ol><h3>Wiring It Up with Maven</h3><p>In your pom.xml, define a default property:</p><pre>&lt;properties&gt;<br>    &lt;app.version&gt;dev&lt;/app.version&gt;<br>&lt;/properties&gt;</pre><p>Pass it to native-image in the GraalVM plugin configuration:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.graalvm.buildtools&lt;/groupId&gt;<br>    &lt;artifactId&gt;native-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;0.10.4&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;mainClass&gt;com.example.Main&lt;/mainClass&gt;<br>        &lt;imageName&gt;mytool&lt;/imageName&gt;<br>        &lt;buildArgs&gt;<br>            &lt;arg&gt;--no-fallback&lt;/arg&gt;<br>            &lt;arg&gt;-Dapp.version=${app.version}&lt;/arg&gt;<br>            &lt;arg&gt;--initialize-at-build-time=com.example.Version&lt;/arg&gt;<br>        &lt;/buildArgs&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>And Et voilà …</p><h3>An Alternative I Considered — And Why I Dropped It</h3><p>Before landing on the --initialize-at-build-time approach, I looked at Maven resource filtering. The idea is straightforward: create a version.properties file in src/main/resources/, put a placeholder in it, and let Maven replace it before compilation.</p><pre># src/main/resources/version.properties<br>version=${app.version}</pre><p>Enable filtering in pom.xml:</p><pre>&lt;build&gt;<br>    &lt;resources&gt;<br>        &lt;resource&gt;<br>            &lt;directory&gt;src/main/resources&lt;/directory&gt;<br>            &lt;filtering&gt;true&lt;/filtering&gt;<br>        &lt;/resource&gt;<br>    &lt;/resources&gt;<br>&lt;/build&gt;</pre><p>Then read it at runtime:</p><pre>Properties props = new Properties();<br>props.load(Main.class.getResourceAsStream(&quot;/version.properties&quot;));<br>String version = props.getProperty(&quot;version&quot;, &quot;dev&quot;);<br>System.out.println(&quot;jbeats &quot; + version);</pre><p>On paper this works. In practice with GraalVM native-image, there are two problems.</p><p><strong>Problem 1: GraalVM doesn’t bundle resources by default.</strong></p><p>native-image does not include classpath resources in the binary unless you explicitly register them. So getResourceAsStream(&quot;/version.properties&quot;) returns null at runtime — the file simply isn&#39;t there. To fix it you need a resource-config.json in src/main/resources/META-INF/native-image/:</p><p>json</p><pre>{<br>  &quot;resources&quot;: {<br>    &quot;includes&quot;: [<br>      { &quot;pattern&quot;: &quot;version.properties&quot; }<br>    ]<br>  }<br>}</pre><p>That’s an extra config file to maintain. Forget it, or get the pattern wrong, and you get a silent null — same symptom as before, no build error to catch it.</p><p><strong>Problem 2: Silent failure if filtering doesn’t run.</strong></p><p>If Maven resource filtering is skipped or misconfigured, the placeholder never gets replaced. Your binary ships with the literal string ${app.version} as its version. Again, no build error — it compiles and links just fine.</p><p>Two extra failure modes, both silent, both producing wrong output rather than a build break. That’s worse than the problem I was trying to solve.</p><p>The --initialize-at-build-time approach fails loudly if something goes wrong — if the property isn&#39;t set, you get dev, which is visibly wrong and easy to catch in CI. It also requires zero extra config files. That&#39;s why I went with it.</p><p>This is the first time I came across --initialize-at-build-time approach and I have to say — i kinda like it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*Ge5xw7P4CMkwLUFj.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b1535c57d6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/baking-a-version-string-into-a-graalvm-native-image-40b1535c57d6">Baking a Version String into a GraalVM Native Image</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What structural fingerprint(clustering) reveals about Go codebases — and what it does not]]></title>
            <link>https://faun.pub/what-structural-fingerprint-clustering-reveals-about-go-codebases-and-what-it-does-not-19c1de6427e2?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c1de6427e2</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 15:44:39 GMT</pubDate>
            <atom:updated>2026-06-18T15:44:39.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zswL5jraBijw_kB-.png" /></figure><h3>Introduction</h3><p>In part 1 <a href="https://medium.com/faun/structural-fingerprint-for-golang-repositories-a-case-study-ae560bafec84">https://medium.com/faun/structural-fingerprint-for-golang-repositories-a-case-study-ae560bafec84</a> we follow a singular question — <strong><em>does vocabulary-independent clustering find real patterns in real codebases</em></strong><em>.</em></p><p>And I introduced <a href="https://github.com/somak2kai/beats">https://github.com/somak2kai/beats</a> that attempts to answer the same.</p><p>As promised in earlier article, i wanted to follow through on the potential applications of evaluating a structural fingerprint. Lets talk through outlier drifts today.</p><p>There is a function in Mattermost’s public Go client that will panic if you call it the way its own signature invites you to. It guards a pointer against nil in one place and then, two lines later, dereferences that same pointer unconditionally. Every other function in its neighborhood handles this correctly. This one didn&#39;t.</p><p>There is a function in Rancher’s GKE integration that forwards an unvalidated, possibly-empty field to Google’s compute API, where every one of its five siblings validates first. Same shape of mistake. Different codebase. Found the same way.</p><p>I found both by measuring the <em>shape</em> of the code — and then reading the one function in each family that didn’t fit.</p><p>This is a writeup of what that means, what it caught, and — just as importantly — what it got wrong, because the things it got wrong are more revealing than the things it got right.</p><p>For the impatient ones the below PRs for Mattermost and Rancher</p><p><em>(full disclosure, at the time of writing this article, they are both pending on reviewers)</em></p><ul><li><a href="https://github.com/mattermost/mattermost/pull/37045">Minor PR: Fixes panic for Client4.GetUsersNotInChannelWithOptions accesses options.Etag outside of if guard by somak2kai · Pull Request #37045 · mattermost/mattermost</a></li><li><a href="https://github.com/rancher/rancher/pull/55552">Minor : Add validation for empty project id and zone similar to other methods in pkg/api/norman/customization/gke/listers.go#listDiskTypes by somak2kai · Pull Request #55552 · rancher/rancher</a></li></ul><h3>What it found</h3><p>I ran beats across ten large Go codebases — Kubernetes, CockroachDB, etcd, gVisor, Terraform, cAdvisor, Gitea, Azure Service Operator, Mattermost, and Rancher , among others — as case-study subjects.</p><p>Most of them came back clean. Not “no outliers” — plenty of outliers — but every outlier, on inspection, turned out to be an intentional, explainable divergence. Audit instrumentation that legitimately added a defer. Count queries whose shape coincidentally overlapped slice-returning peers. App-layer functions that matched store-layer clusters only through shallow token coincidence. All explainable. All fine.</p><p>Two were not fine. And they were the same kind of mistake.</p><h3>Mattermost: a nil dereference on a public API</h3><p>Client4.GetUsersNotInChannelWithOptions was flagged as an outlier in a cluster of roughly thirty client functions that all follow the same pattern: build up query values, then pass an etag string to doAPIGetWithQuery. Every other function in that cluster accessed its etag safely — either as a plain string parameter or inside a nil-guarded block. This one function reached for options.Etag <em>outside</em> its own nil guard:</p><pre>if options != nil {<br>    values.Set(&quot;in_team&quot;, options.TeamID)<br>    // ... more values<br>}<br>r, err := c.doAPIGetWithQuery(ctx, c.usersRoute(), values, options.Etag) // options is nil-guarded above, dereferenced here</pre><p>The function takes a pointer, *GetUsersNotInChannelOptions. The body nil-guards it — which signals to a caller that nil is an acceptable input. And then it dereferences that pointer unconditionally. Pass nil, and the client panics before it ever makes an HTTP request.</p><p>Today the only caller passes a non-nil struct, so this has never crashed in production. But it sits on server/public/model/ — a public API surface — and the contract it advertises (nil is fine) is contradicted by the code (nil panics). The fix is one of the smallest possible: hoist the etag into a local, assign it inside the guard, pass the local. It makes the outlier conform to the convention its thirty peers already follow.</p><p><a href="https://github.com/mattermost/mattermost/pull/37045">Minor PR: Fixes panic for Client4.GetUsersNotInChannelWithOptions accesses options.Etag outside of if guard by somak2kai · Pull Request #37045 · mattermost/mattermost</a></p><h3>Rancher: a missing validation guard</h3><p>listDiskTypes, in Rancher&#39;s GKE customization listers, was flagged as the sole outlier in a family of cloud listers — listMachineTypes, listNetworks, listSubnetworks, listServiceAccounts, listVersions — that all open by validating their required capability fields before touching the compute client. listMachineTypes, its closest structural twin, uses the identical List(projectID, zone) signature and guards both fields up front. listDiskTypes had no such guard and called straight into the client.</p><p>When either field is empty, the generated Go client interpolates them into the URL template projects/{project}/zones/{zone}/diskTypes, producing a malformed request (projects//zones//diskTypes). The GCE API rejects this, and Rancher wraps the Google error as a 500 Internal Server Error with &quot;failed to list disk types&quot; — instead of the 400 Bad Request that every sibling lister returns for missing fields.</p><p>Both project and zone are documented as required path parameters in the <a href="https://cloud.google.com/compute/docs/reference/rest/v1/diskTypes/list">GCE REST API reference</a></p><p><a href="https://github.com/rancher/rancher/pull/55552">Minor : Add validation for empty project id and zone similar to other methods in pkg/api/norman/customization/gke/listers.go#listDiskTypes by somak2kai · Pull Request #55552 · rancher/rancher</a></p><h3>What this is, and what it isn’t</h3><p>The goal of creating beats was never to find bugs or hunt for them. I want to be careful not to oversell this, because the honest version is more useful than the inflated one.</p><p>What it is: a way to measure a layer of a codebase that existing Go tooling doesn’t touch. Duplicate detectors work at the token level. Linters and type checkers work on one function at a time. None of them ask how a function relates <em>structurally</em> to the rest of the codebase — and that relationship is where conventions, drift, and the occasional real defect all live.</p><p>Lets cover some of the outliers that beats uncovered in different repositories and why those outliers are explainable deviations.</p><p>The more instructive material is everything that <em>are explainable deviations</em> — because every one of these is the tool correctly flagging a structural deviation and a human correctly deciding it wasn’t a worry.</p><p><strong>Mattermost — </strong><strong>getTeamsUsage.</strong> <em>Real deviation- </em>that set an error on a nil check and then <em>failed to return</em> — falling through to marshal a nil value into the response body as the literal bytes null, even though an error had just been set. When I traced the function it depends on, App.GetTeamsUsage, I found that it only ever returns a nil usage value <em>together with</em> a non-nil error. The handler checks the error first and returns there</p><p><strong>Consul — </strong><strong>bimapper.UntrackItem.</strong> <em>False positive.</em> Flagged for missing a !wildcardLink guard that three sibling functions have. But those siblings check the <em>link</em> type, where a wildcard is meaningful; UntrackItem checks the <em>item</em> type, which is never a wildcard. The asymmetry is by design. The cluster pooled functions that look alike but answer different questions.</p><p><strong>Consul — </strong><strong>caConfigTxn.</strong> <em>Real, low-severity.</em> A type assertion on a store lookup returns &quot;no config&quot; for both the genuine empty case and the corrupted-wrong-type case, swallowing the latter. In practice the wrong-type case only arises from a programmer error writing the wrong type into the table, so it&#39;s a clarity issue, not a runtime risk.</p><p><strong>Nomad — </strong><strong>upsertHostVolumeForNode.</strong> <em>Real deviation, likely intentional.</em> One switch arm is empty where its siblings actively transition state. The volume is deliberately reinserted with its original state and an updated pool assignment. The honest flag is &quot;this deserves a comment,&quot; not &quot;this is a bug.&quot;</p><p><strong>Elastic Agent — </strong><strong>GetPackageName / </strong><strong>GetRootDir.</strong> <em>Real deviation, defensible.</em> These panic instead of returning an error like their cluster peers. But they operate on build-time templates from config files, where a failure is a programmer error. Whether it&#39;s a &quot;concern&quot; depends entirely on whether you want uniform signatures across dev-tooling code.</p><p>I could go on and on, but hopefully this provides a snapshot of beats does and can achieve.</p><p><a href="https://github.com/somak2kai/beats">beats</a> is open source. If you run it on your own codebase, I’d genuinely like to know what it finds — including the outliers that turn out to be nothing. Those are data too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*-LF2Udv0Kic_dkUN.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c1de6427e2" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/what-structural-fingerprint-clustering-reveals-about-go-codebases-and-what-it-does-not-19c1de6427e2">What structural fingerprint(clustering) reveals about Go codebases — and what it does not</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Encode/Txn/Decode in BadgerDB. Use badgerx Instead]]></title>
            <link>https://faun.pub/stop-writing-encode-txn-decode-in-badgerdb-use-badgerx-instead-9a74eb1cc32d?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a74eb1cc32d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[badgerdb]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Wed, 27 May 2026 09:13:40 GMT</pubDate>
            <atom:updated>2026-06-03T12:58:46.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TXXmh13EHpqTQAj1pTPgg.png" /></figure><p><a href="https://github.com/dgraph-io/badger">BadgerDB</a> is genuinely one of my favorite libraries in the Go ecosystem. Fast, embeddable, pure Go, ACID transactions — it’s the kind of dependency you add and never regret. I’ve used it across a few projects now, and it’s never let me down.</p><p>But there’s a tax you pay every single time you use it.</p><p>BadgerDB speaks `[]byte`. Your application speaks structs. And the translation layer between the two — encode, open transaction, set, commit, open transaction again, get, copy value out before it’s gone, decode — that’s yours to write.</p><p>I didn’t notice it on the first project. The second time I started copy-pasting the same patterns and thought, “I’ll clean this up later.” Later in engineering almost translates to never, this time i thought i want to break my pattern. That’s the point I stopped and wrote <a href="https://github.com/somak2kai/badgerx">badgerx</a>.</p><h4>What the boilerplate actually looks like</h4><p>Here’s a completely typical pair of store/load methods from a real application. Nothing exotic — just persisting a `User` struct:</p><pre>func (d *MyDb) StoreUser(id string, u User) error {<br>    var buf bytes.Buffer<br>    if err := gob.NewEncoder(&amp;buf).Encode(u); err != nil {<br>        return err<br>    }<br>    return d.db.Update(func(txn *badger.Txn) error {<br>        return txn.Set([]byte(&quot;user:&quot;+id), buf.Bytes())<br>    })<br>}<br><br>func (d *MyDb) LoadUser(id string) (User, error) {<br>    var u User<br>    err := d.db.View(func(txn *badger.Txn) error {<br>        item, err := txn.Get([]byte(&quot;user:&quot; + id))<br>        if err != nil {<br>            return err<br>        }<br>        return item.Value(func(val []byte) error {<br>            return gob.NewDecoder(bytes.NewBuffer(val)).Decode(&amp;u)<br>        })<br>    })<br>    return u, err<br>}</pre><p>That’s some number of lines for one type. Now imagine you have multiple types you would want to save. Each one needs its own pair of methods. Each pair is structurally identical — only the type name changes.</p><p>The worst part isn’t the lines of code. It’s that you’re making the same decisions at every call site: which encoder? handle the transaction correctly?</p><h4>What badgerx does instead</h4><pre>xdb := badgerx.NewBadgerXDb(db)<br>defer xdb.Close()<br><br>// store<br>_ = xdb.Update([]byte(&quot;user:1&quot;), u)<br><br>// retrieve<br>var got User<br>_ = xdb.View([]byte(&quot;user:1&quot;), &amp;got)</pre><p>That’s it.</p><p>The encoding, the transaction, the value copy — all handled. <em>Update</em> encodes then writes. <em>View</em> reads, decompresses if needed, then decodes.</p><h4>Iterating over a prefix</h4><p>This is the one that saved me the most typing. The full iterator pattern in raw BadgerDB is verbose:</p><pre>err := db.View(func(txn *badger.Txn) error {<br>    opts := badger.DefaultIteratorOptions<br>    it := txn.NewIterator(opts)<br>    defer it.Close()<br>    prefix := []byte(&quot;user:&quot;)<br>    for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {<br>        item := it.Item()<br>        err := item.Value(func(val []byte) error {<br>            var u User<br>            return gob.NewDecoder(bytes.NewBuffer(val)).Decode(&amp;u)<br>        })<br>        if err != nil {<br>            return err<br>        }<br>        // do something with u... but u is scoped awkwardly here<br>    }<br>    return nil<br>})</pre><p><strong>With badgerx:</strong></p><pre>var users []User<br>err := xdb.IterateView([]byte(&quot;user:&quot;), badger.DefaultIteratorOptions,<br>    func(decode badgerx.DecodeFunc) error {<br>        var u User<br>        if err := decode(&amp;u); err != nil {<br>            return err<br>        }<br>        users = append(users, u)<br>        return nil<br>    },<br>)</pre><p>The <em>DecodeFunc</em> pattern here is intentional. The ownership is clear, there’s no shared state between iterations, and returning an error from the callback stops iteration immediately and surfaces that error as the return value of <em>IterateView</em>.</p><p>The <em>opts</em> parameter gives you full control over iteration behaviour — reverse order, keys-only mode, prefetch tuning — by passing a <em>badger.IteratorOptions</em> directly.</p><h4>The pieces worth knowing about</h4><h4>Pluggable encoding</h4><p>The default encoder is <em>gob</em> — no configuration needed.</p><p>If you need human-readable storage, or you’re reading values from a non-Go service, switch to JSON with one option:</p><pre>xdb := badgerx.NewBadgerXDb(db,<br> badgerx.WithEncoder(&amp;badgerx.JsonEncoderDecoder{}))</pre><p>Want msgpack, protobuf, or something custom? Implement two methods:</p><pre>type Encoder interface {<br>    Encode(v any) ([]byte, error)<br>    Decode(data []byte, v any) error<br>}</pre><p>Pass it in with `WithEncoder` and you’re done. The rest of the library doesn’t care what format you use.</p><h4>Compression</h4><p>Three options ship out of the box. By default there’s no compression( important for values) — zero overhead, good for most use cases. When you’re storing large values and storage size matters:</p><pre>// Zstandard — best ratio, fast decompression<br>zstdC, _ := badgerx.NewZstdCompressor()<br>xdb := badgerx.NewBadgerXDb(db, badgerx.WithCompressor(zstdC))<br>defer xdb.Close() // releases zstd encoder/decoder<br><br>// Snappy — fastest, moderate ratio<br>xdb := badgerx.NewBadgerXDb(db, badgerx.WithCompressor(&amp;badgerx.SnappyCompressor{}))</pre><p>I benchmarked all six encoder/compressor combinations against a realistic struct — 100 sessions, 200 audit log entries, nested addresses, maps, timestamps — on an Apple M1 Pro. The numbers were more interesting than I expected.</p><p><strong>Storage (bytes on disk after encoding + compression):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSR8787wD8hDCehZh4I8rQ.png" /></figure><p><strong>Read latency (ns/op, Apple M1 Pro, `go test -bench -benchtime=5s`):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnEkVWo9WTenk2s6Pq-tjg.png" /></figure><p>A few things worth calling out.</p><ul><li>First, <strong>gob+snappy reads faster than no compression at all </strong>— 100µs vs 132µs. The smaller payload means less I/O, and snappy decompression is cheap enough that you come out ahead. It’s a free lunch on reads.</li><li>Second, <strong>gob+zstd adds almost nothing to read latency</strong> — 138µs vs 132µs, a 4.6% difference — while shrinking storage by 6.4x. If you’re storing anything beyond trivial values, this is probably the right default.</li><li>Third, <strong>gob decodes 3.5x faster than JSON</strong> on this data (132µs vs 469µs). JSON is the right choice when you need human-readable storage or cross-language access, but if it’s Go talking to Go, gob is significantly faster to decode.</li></ul><p>This is value-level compression applied before BadgerDB stores anything — it stacks on top of, and is complementary to, BadgerDB’s own storage-level block compression. You can use both simultaneously.</p><h4>Structs with interface{} fields</h4><p>One place `gob` requires a bit of setup: if your struct has an `interface{}` or `any` field, gob needs to know the concrete type that will appear there at runtime. badgerx exposes this cleanly:</p><pre>type Event struct {<br>    Name    string<br>    Payload any  // could be LoginPayload, CheckoutPayload, etc.<br>}<br><br>enc := &amp;badgerx.GobEncoderDecoder{}<br>enc.RegisterType(LoginPayload{})<br>enc.RegisterType(CheckoutPayload{})<br><br>xdb := badgerx.NewBadgerXDb(db, badgerx.WithEncoder(enc))</pre><p>Call <em>RegisterType</em> once at startup for each concrete type that might appear in an interface field. After that, encode and decode work exactly as you’d expect.</p><p>Important, this is <em>gob.Register</em> under the hood — badgerx just gives you a typed home for it rather than scattering global calls around your codebase.</p><h4>What badgerx doesn’t do</h4><p>To be fully transparent - badgerx wraps <em>Update</em> and <em>View . </em>It does not re-wrap BadgerDB’s full API — no TTL helpers, no batch writer, no subscription wrappers.</p><p>This is deliberate. The goal was to remove the one piece of boilerplate that every BadgerDB application writes and rewrites — not to build an ORM on top of a key-value store.</p><h4>Installing</h4><pre>go get github.com/somak2kai/badgerx</pre><p>Requires Go 1.23 or later. Full docs <a href="https://pkg.go.dev/github.com/somak2kai/badgerx">here</a>.</p><p>If you’re already using BadgerDB in a project, the migration is additive — wrap your existing <em>badger.DB</em> with <em>badgerx.NewBadgerXDb</em> and start using Update/ View for any new types. The underlying database is unchanged.</p><p>You can also view a usage pattern here <a href="https://github.com/somak2kai/beats/blob/main/pkg/db/db.go">https://github.com/somak2kai/beats/blob/main/pkg/db/db.go</a></p><p>If you’ve been copy-pasting the same encode/txn/decode pattern across your BadgerDB code, give it a try. And if something doesn’t work the way you’d expect, open an issue — the project is new enough that feedback actually shapes it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*_vuNrXTfBwopb2Xb.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z7i6gKASFZFILQay.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN.dev() &amp; get similar stories in your inbox each week for free!</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a74eb1cc32d" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/stop-writing-encode-txn-decode-in-badgerdb-use-badgerx-instead-9a74eb1cc32d">Stop Writing Encode/Txn/Decode in BadgerDB. Use badgerx Instead</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Fingerprint for Golang Repositories — A Case Study]]></title>
            <link>https://faun.pub/structural-fingerprint-for-golang-repositories-a-case-study-ae560bafec84?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae560bafec84</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Sun, 24 May 2026 08:23:23 GMT</pubDate>
            <atom:updated>2026-06-18T15:45:25.811Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><h4>Measure structural fingerprint for a codebase</h4><h4>Verify structural fingerprint for a codebase</h4><h4>Introducing Beats</h4><h4>Practical applications for fingerprints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHtTMRvaTvup5GLQn11yVg.png" /></figure><p>Part 2 here <a href="https://medium.com/@somaktukai/what-structural-fingerprint-clustering-reveals-about-go-codebases-and-what-it-does-not-19c1de6427e2">https://medium.com/@somaktukai/what-structural-fingerprint-clustering-reveals-about-go-codebases-and-what-it-does-not-19c1de6427e2</a></p><p>I am fascinated by shapes , they intrigue me .</p><p>A visual imprint can become so clear/ingrained it can help you navigate in the dark. So naturally , i was like <em>oooohh! </em>does this happen for codebase as well? And thereby —</p><blockquote><strong><em>does vocabulary-independent clustering find real patterns in real codebases</em></strong>.</blockquote><p>Well if you think about it, every time you are writing code, reviewing code you are implicitly but invariably putting them into familiar or new shapes. More often than not, these shapes are learnt, set as guidelines or enforced in pr reviews over time, judiciously. And said shapes would/may change based on design decisions , language frameworks or dependencies syntax / constraints, architectural decisions, ownership from project to project, domain to domain and organization to organization.</p><p>So I ran a completely self-inflicted, zero-incentive experiment to answer this.</p><ul><li>How can you define and measure structural fingerprint for a codebase</li><li>How to verify / test correctness of said structural fingerprint</li><li>What practical applications does this uncover.</li></ul><p>In the interest of brevity, we would just softly touch on each of the above. Subsequent articles would have deep dives, code examples, my git project link, data from real enterprise projects to ponder/ question / judge / dispute / dismiss and all similar good things.</p><h3>Introducing Beats</h3><p>The code used to generate the above reports is available here</p><p><a href="https://github.com/somak2kai/beats">https://github.com/somak2kai/beats</a></p><p>Instructions for download and execution are available in readme for the repo.</p><h3>To keep you reading..</h3><p>A small incentive to keep you reading</p><p>Here is beats reports on few open source projects <a href="https://somak2kai.github.io/beats/">https://somak2kai.github.io/beats/</a></p><p><strong>Additionally,</strong></p><p><a href="https://github.com/scip-code/scip">https://github.com/scip-code/scip</a> is a language-agnostic protocol for indexing source code, which can be used to power code navigation. Its industry known and a brilliant piece of technology.</p><p>No shade to scip, I actually considered them touch stone.</p><p>As in, whatever tool i am building to identify structural fingerprints ( psstt.. i named my tool <strong><em>beats</em></strong>) , if there is an agreement &gt;40% of the time with my results. I could probably breathe easy , my direction feels well steered.</p><p>If my tool ( psstt..<strong><em>beats</em></strong>) can provide more controlled concrete answers to queries compared to scip, I could probably breathe easy , my direction feels well steered.</p><p>Tldr here are the comparison results for</p><pre>https://github.com/mattermost/mattermost<br>https://github.com/go-gitea/gitea</pre><p><em>Others such as cockroachdb/parca/k8s/etcd/linkerd were all used, i am presenting a snapshot here ( most tight product repos eg k8s form really good cluster coherence, and i wanted to present results from some potential disparate repos)</em></p><p><strong>Takeaway</strong> : SCIP agrees with <strong><em>beats </em></strong>vocabulary independent clustering logic <strong>&gt; ~85%</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Rq4vx0eJprYVuHKATGHQg.png" /></figure><p><strong>Recall answers</strong>:</p><ul><li>does SCIP confirm the cluster?</li><li>A recall of 1.00 means every function beats grouped is reachable via those SCIP queries — SCIP agrees the cluster is coherent</li></ul><p><strong>Precision answers</strong>:</p><ul><li>is beats more focused than SCIP?</li><li>Measures what fraction of the SCIP query result is actually inside the beats cluster.</li></ul><p>If you are interested in reading more here is a <a href="https://somak2kai.github.io/beats/beats-validation.html">readout</a></p><h3>Measure structural fingerprint for a codebase</h3><p><em>Remember the goal: find meaningful patterns in code by looking at what it does structurally — not its semantic meaning/vocabulary</em></p><p>I have chosen to define structural fingerprint for a codebase as below:</p><ol><li>For each function calculate token sequence, where each token is an AST mnemonic, eg CALL for a another function call, ASSIGN for var assignment, RETURN for return statements with arity, etc.</li><li>For each function, get the fan out statements — Call Target.</li><li>For each function, get the import statements utilized within the function.</li><li>There will be no attempt to know what a call target does or what an import statement does, because that defeats our original goal.</li></ol><p>Each of these ( along with some other metadata) are named FunctionMetadata.</p><p>Once we have the FunctionMetadata across golang codebase, we perform a specific algorithm to cluster them into meaningful patterns.</p><p>I used a weighted pattern,</p><ul><li>tokens match across function metadata weighted 50%</li><li>jaccard similarity between import statements weighted 30%</li><li>jaccard similarity between call target weighted 20%</li></ul><p>The output is N number of clusters, each with a coherence value ( how tight the function metadata within it are) <em>there is more to it, but like i said, for sake of brevity…</em></p><h3>Verify structural fingerprint for a codebase</h3><p>Once again we would take examples of the below repositories</p><pre>https://github.com/mattermost/mattermost<br>https://github.com/go-gitea/gitea</pre><p>A typical report generated by beats takes close to ~4–5secs to generate and looks like so</p><p>Lets look at Mattermost first</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x43UWpVQO5lk44juhThq8w.png" /></figure><p>Mattermost golang code stats sits at</p><pre>-------------------------------------------------------------------------------<br>Language                     files          blank        comment           code<br>-------------------------------------------------------------------------------<br>Go                            2205         121540          36206         634727</pre><p>We of course ignore auto generated code such as pb.go, unit tests files and run beats clustering logic on mattermost golang code.</p><p>Key takeaway:</p><ul><li>The job scheduler contract — beats discovered an unwritten codebase law. Cluster 9ba0de0e8d56b028 with coherence of 1.0 spans 9 different job packages, uncovering a pattern for background jobs.</li></ul><pre>func MakeScheduler(jobServer *jobs.JobServer) *jobs.PeriodicScheduler {<br> isEnabled := func(cfg *model.Config) bool {<br>  return *cfg.MetricsSettings.Enable<br> }<br> return jobs.NewPeriodicScheduler(jobServer, model.JobTypeActiveUsers, schedFreq, isEnabled)<br>}</pre><ul><li>Interestingly another example of a scheduler lands in a different cluster, because its license gated with observability logging. Is that good or is that bad? I dont know yet. But i can say its based on my current design.</li></ul><pre>func MakeScheduler(jobServer *jobs.JobServer, license *model.License) *jobs.PeriodicScheduler {<br> isEnabled := func(cfg *model.Config) bool {<br>  enabled := license != nil &amp;&amp; *license.Features.Cloud<br>  mlog.Debug(&quot;Scheduler: isEnabled: &quot;+strconv.FormatBool(enabled), mlog.String(&quot;scheduler&quot;, model.JobTypeLastAccessibleFile))<br>  return enabled<br> }<br> return jobs.NewPeriodicScheduler(jobServer, model.JobTypeLastAccessibleFile, schedFreq, isEnabled)<br>}</pre><ul><li>The server cleanup loop — identical shape across semantically unrelated operations (f79627f23384617b). runCommandWebhookCleanupJob/runSessionCleanupJob, etc .These clean up completely different things — webhooks, configs, sessions, tokens. They have nothing in common by name or domain. Coherence 1.00 on both axes. beats found the recurring structural idiom: a timed cleanup loop registered on server startup. This is exactly the kind of pattern a developer writing a new cleanup job should know exists before writing their own version.</li><li>To honor full transparency, there are of course noise- clustering of methods that looks like so. The root causes are: (a) generic utility skeletons like simple string formatters have no meaningful import vocabulary to discriminate them; (b) very low cyclomatic complexity (1.0 here) means the token sequence is too short to be distinctive; ( c) standard library-only imports like fmt are too broad a signal. These clusters are not bugs — they are the honest boundary of what structural fingerprinting can claim.</li></ul><pre>func EmailInviteWithErrorToString(o *EmailInviteWithError) string {<br> return fmt.Sprintf(&quot;%s:%s&quot;, o.Email, o.Error.Error())<br>}<br>func TeamMemberWithErrorToString(o *TeamMemberWithError) string {<br> return fmt.Sprintf(&quot;%s:%s&quot;, o.UserId, o.Error.Error())<br>}</pre><p>Now lets look at Gitea</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSOrgbb9ig8iGVJxuahMkQ.png" /></figure><ul><li>Webhook config deserialization — same shape, five different integrations (561da6bf80a4bec2) GetDiscordHook, GetMatrixHook, GetPackagistHook, GetSlackHook, GetTelegramHook — five functions, each living in its own file (discord.go, matrix.go, packagist.go, slack.go, telegram.go), all deserializing a webhook provider&#39;s stored config from a JSON blob into a typed struct. Perfect coherence on both axes. This cluster is directly actionable for security: if there is a deserialization bug or a missing validation step in one of these functions, all five are candidates. The blast radius is the cluster, not the file.</li><li><strong>Password hasher factory — a security-critical structural pattern</strong> (532d2525dd28fcc2) NewArgon2Hasher, NewPBKDF2Hasher, NewScryptHasher — three constructors for different password hashing algorithms, each in its own file. This cluster matters for security not because of the algorithm differences but because of the shared setup shape. If the parameter parsing logic that controls work factors (cost, iterations, memory) has a defect, it&#39;s present in all three. beats identifies them as a unit, without any instructions or specific ask to do so.</li></ul><blockquote><strong>Please note :</strong></blockquote><p>Clustering is a function of multiple parameters such as ignoring token sequences below a certain threshold, or weights among others. The current defaults were calibrated on mid-sized Go codebases and will be iterated. What doesn’t change between versions is the core property: if two functions land in the same cluster, their structural skeleton is genuinely similar. The algorithm can miss patterns; it doesn’t fabricate them</p><h3>Practical applications of structural fingerprint</h3><blockquote><strong>I am going to sound deliriously optimistic here, fair warning</strong></blockquote><p>If you can measure something, you can make judgements around it, you can enforce it.</p><p>What it means for structural fingerprint is — i see the below potential scenarios where <strong><em>beats</em></strong> may help</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98j9WUleDQNV0lPYHro12g.png" /></figure><p>CVE Blast Radius</p><ul><li>When a CVE drops for a library, security teams grep for import statements. But structural fingerprints already know which functions <em>*use*</em> that library in the same <em>*way*</em>. If a CVE affects a specific usage pattern (not just any usage), the cluster sharing that usage pattern is your blast radius. Functions that import the same library but belong to a different structural cluster probably aren’t affected.</li></ul><p>SAST Triage Multiplier</p><ul><li>The biggest complaint about static analysis security tools is the false positive rate. A rule says “flag any function that takes user input and passes it to a database query” and it flags 200 functions, of which 180 are perfectly safe because they use parameterized queries or the input was already sanitized upstream. A security engineer then triages all 200, one at a time. Structural fingerprints <strong>turn one triage decision into many</strong>. If a human marks `getStoreCollection` as a false positive, and that function belongs to a structural cluster of 15 functions that all share the same shape — all 15 are almost certainly false positives too. One decision, fifteen resolutions. That’s a <strong>triage multiplier</strong>.</li></ul><p>True positive propagation</p><ul><li>A confirmed vulnerability in one function — the same structural cluster means other functions likely share the same flaw, potentially across different packages. One confirmed finding becomes multiple high-confidence candidates for the same fix, surfaced automatically without writing a new rule.</li></ul><p>Bug propagation confidence</p><ul><li>In case code across different domains/boundaries followed a certain said/unsaid template and a bug gets raised, what confidence do we have other areas in the codebase hasn’t carried the weight of the baked in bug. Structural fingerprints across code, can help you get there.</li></ul><p>Malicious drift detection</p><ul><li>A function whose structural shape has no precedent in the codebase is an opportunity to ask and reflect — Do large drifts from established conventions(structures) point towards potential malicious intent.</li></ul><p>Architectural pattern finding</p><ul><li>Clusters reveal design decisions that were never written down. The cron task registration pattern, the migration function shape, the retry wrapper idiom — these emerged from the codebase, not from a spec. beats surfaces them so you can name them, document them, and reference them in code review.</li></ul><p>PR drift blocking</p><ul><li>In CI, check whether new functions structurally resemble the established cluster for that subsystem. A service-layer function that looks structurally like a handler is a soft signal of misplacement. Not a hard block — but a prompt: ‘this function’s shape has no precedent in this layer, is that intentional?’</li></ul><p>Migration target discovery</p><ul><li>A team decides to standardise error wrapping, transaction handling, or context propagation across a large codebase. Grep fails when the old pattern has no consistent vocabulary. Structural fingerprints find every function that implements the old shape regardless of what names were used. That’s your migration list.</li></ul><p>Convention standardisation</p><ul><li>Once a canonical pattern is established — error wrapping, context passing, timeout handling — beats can enforce it. New code that deviates structurally from the cluster it should belong to gets flagged. Not because of vocabulary, but because the skeleton itself doesn’t match what the team agreed on.</li></ul><h3>Final Word</h3><p>Beats has shown to perform best on codebases with strong internal conventions — repositories like CockroachDB, Kubernetes, and Linkerd, where architectural discipline is high and patterns repeat deliberately. In these codebases, structural fingerprinting borders on self-evident: the conventions are already there, beats simply makes them explicit and queryable.</p><p>The harder problem — not having access to massive golang repositories with disparate, varying use cases to solve has proved to be a challenge. The messy middle: production codebases that grew organically, where conventions exist but were never written down, and where structural patterns are real but noisy. Gitea and Mattermost are closer to this reality. The results there are less clean, but arguably more valuable.</p><p>Additionally, a structural fingerprint tells you what the codebase has quietly agreed on. It doesn’t tell you whether that agreement was a good idea. That gap is intentional — beats is a lens, not a prescription. At least at the moment.</p><p>There is work to be done and i would be tracing each of the potential use cases against <strong><em>beats </em></strong>and be honest about its claims, where it succeeds and where it fails. Beats also needs a query layer and I want to see how far AI usage can take ahead beats.</p><p>If you have read this far and followed along, you may be interested in what comes next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/0*nR2MwMe418eTmOUN.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z7i6gKASFZFILQay.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN.dev() &amp; get similar stories in your inbox each week for free!</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae560bafec84" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/structural-fingerprint-for-golang-repositories-a-case-study-ae560bafec84">Structural Fingerprint for Golang Repositories — A Case Study</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ye Old Ball n Chain]]></title>
            <link>https://medium.com/@somaktukai/ye-old-ball-n-chain-f1daaa706d4?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1daaa706d4</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Sat, 27 May 2023 16:39:23 GMT</pubDate>
            <atom:updated>2023-05-27T16:50:46.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*-VqlX8WayodJVPA_mO-2FQ.png" /></figure><p>Setup</p><p>If there is anyone here i have had the privilege to work with, they would know i absolutely love me some design patterns. I love learning about them, i love using them, i love debating one against the other and i love the consequence of using them.</p><p>The consequence of using them? Code that is demonstrably beautiful, clean, reusable, extensible, testable and readable.</p><p>I have very successfully applied patterns like factory, abstract factory, builder, adapter, command, observer, strategy, singletons in my work places before ( psst.. i have a very special place in my heart for command pattern) .</p><p>Lets hear it for another behavioural pattern.. urf <strong>Chain of Responsibility pattern.</strong></p><p>This post is just about presenting the Chain of responsibility behavioural design pattern. This is not a recommendation as no pattern can be recommended without full understanding of a use case .</p><p>Quick Use Case</p><p>Say you have a block of wood, unprocessed and unusable.</p><p>You want to convert it to a blocks of wood, say 3 by 8?</p><p>You have a bunch of machines at your disposal which can process the wood , say Machine A can only process a specific kind of wood, Machine B can only process other kind, Machine C can perform cutting it into sizes, Machine D can apply mahogany polish where as Machine E can apply light bleach polish and so on and so forth.</p><p>You do not want to manually inspect and remember which machine does what and you definitely do not want to individually carry the unprocessed/semi processed woods to the correct machines.</p><p>You would want a pipeline. You give it your unprocessed wood ( <strong>input</strong> ) , you let the pipe line do what it does ( <strong>behaviour</strong> ) and you expect the block of wood in return (<strong>output</strong> )</p><p>Solution 1</p><p>Lets write some bunch of code to solve the problem.</p><p>At the very least we would need an input class, an output class and a bunch of other code that performs the processing.</p><p><strong>Input Class</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd38460bd73a279bae0bf635caf47176/href">https://medium.com/media/fd38460bd73a279bae0bf635caf47176/href</a></iframe><p><strong>Output Class</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9c9f971580b789b07115cdf7eff41b/href">https://medium.com/media/7f9c9f971580b789b07115cdf7eff41b/href</a></iframe><p>The easy parts done. Now comes the main logic. Lets write some dumb code now, something we can iterate to good stuff later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/510649fb237f228433e4e0a877ff7ff4/href">https://medium.com/media/510649fb237f228433e4e0a877ff7ff4/href</a></iframe><p><em>Now i know none of you would ever everrrrr write code like that, but indulge me for a minute.</em></p><p>What are the potential issues for the above code:</p><ol><li>Too much happening at the same time. We have one single method that does the input validation, that does the wood processing, that performs the polishing.</li><li>Not extensible, over time would become cumbersome to maintain.</li><li>Difficult to test.</li></ol><p>Solution 2</p><p>You have a first draft solution ready with you above and you smart people also know/ or can foresee the issues with the above codebase.</p><p>So you say non- cohesive? Lets break it up into classes that have individual responsibility.</p><p>So you create beautiful templates using abstract classes or interfaces and you create individual concrete implementations for the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed49443333e28241f29bf2944314962c/href">https://medium.com/media/ed49443333e28241f29bf2944314962c/href</a></iframe><p>And because you are savvy and a good coder, you decide to use Dependency Injection to inject such behaviour at runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b76ef6b71079a7a6c78032395e7a5809/href">https://medium.com/media/b76ef6b71079a7a6c78032395e7a5809/href</a></iframe><p>Baam!! Cohesion ..done.. testable..done.. maintainable done.</p><p>Till you realize, how unwieldy your client has become now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb01c6f53b01c8cf7c4d0b90faf325a/href">https://medium.com/media/7cb01c6f53b01c8cf7c4d0b90faf325a/href</a></iframe><p>Your client is now aware of what type of saw to use under which conditions.</p><p>Solution 3: Using Chain of Responsibility</p><p>As with any behavioural patterns, all we need to do is to extract out the behaviours into stand alone objects. We are half way there already.</p><p>What has become apparent by now is, we have objects that each perform a specific <strong>responsibility</strong> and when <strong>chained</strong> together we would get the final product or outcome.</p><p>We call these individual classes our handlers and we chain them together in sequence to get the final result. Along the way we also follow some best practices to reduce boiler plate code. Lets get to it.</p><ol><li>We rename our classes to be ~Handlers.</li><li>We realize that the only input we require is unprocessed wood and the dimensions that we want. We can simplify our handlers accordingly.</li><li>We figure out a way to chain these together to form a pipeline.</li></ol><p>We first create a template for our handlers to follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77ba30caa83e2afcae8af9a3d81751d4/href">https://medium.com/media/77ba30caa83e2afcae8af9a3d81751d4/href</a></iframe><p>We then abstract out some of the boiler plate code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6395ea4b59b695d717e9949769c86ff3/href">https://medium.com/media/6395ea4b59b695d717e9949769c86ff3/href</a></iframe><p>We create concrete implementations for the handlers now</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1182d76a4b8529c3a56cbd8765168cc2/href">https://medium.com/media/1182d76a4b8529c3a56cbd8765168cc2/href</a></iframe><p>And finally we chain them together and create a pipeline</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2242ca7dc9cea02fdf1fd4927e230e8/href">https://medium.com/media/b2242ca7dc9cea02fdf1fd4927e230e8/href</a></iframe><p>We did a bunch of things, lets walk through it:</p><ol><li>We created an interface/ abstraction for all our handlers to follow</li><li>The logic to either get the results as and when available or else proceed to the next configured in the pipeline is also in the abstraction</li><li>We create tiny handlers that does one thing and one thing only as concrete implementations of the abstractions in point 1.</li><li>The client then instantiates the handlers and sets up the pipelines using setNext() method</li><li>Our existing framework would take care to return once available or proceed to the next if not.</li></ol><p>Philosophical Debates</p><p>The above presents one way of implementing the chain of responsibilities pattern.</p><p>There are many ways the pattern can be created. You could very well have the client instantiate a list of handlers that runs in sequence to create the output.</p><p>Now , the main thing. <em>Our clients are aware of the handlers to create.</em></p><p>yes yes yes! You are correct. You can use as many design patterns you want/ as much configurations you want, but the sheer fact remains client needs to be aware of the handlers to create.</p><p>So when should we be using this pattern and when not.</p><p><strong>When to use:</strong></p><ol><li>This pattern provides a nice way of creating a “launch and leave” kind of pattern.</li><li>If you have a smaller subset of choices to make and instantiation of handlers are not expensive, you may use this pattern.</li><li>However if you compare our solution2 vs solution 3, you would find that in solution 2, the clients are deciding the logic as to when to use a power saw vs an easy saw. We dont have the same issue in solution 3. If solution3, we can just change an if clause in one place and every single one of our clients would get uniformed processing logic.</li></ol><p><strong>When not to use:</strong></p><ol><li>If client is directly aware of which handler can process the request, this pattern becomes an over engineered solution. Might as well call the handler directly</li><li>If there are too many chains and creation of these handlers are expensive, you definitely do not want to have them pre created or for that matter even create them ( since it would resource wastage)</li></ol><p>Overall i find Command pattern to be a much more evolved and better pattern to use.</p><p>Rant</p><p>Does anyone care about design patterns these days? Does your manager? Does your seniors or juniors? Does your stakeholders? Does your customers?</p><p><strong>NO</strong></p><p>They dont.</p><p>And if you ask me , i think there is validity to the argument that they should not.</p><p>But as a developer you should. Creation of good clean code is craftmanship. There is a bit of art in it, it takes patience, it takes skills , it takes learnings to come up with good code.</p><p>In the world of open source frameworks readily available, chat gpt, etc etc no one will give you a gold medal just because you used a good design pattern.</p><p>However like i said, its craftmanship.</p><p>The rest is upto you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1daaa706d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tinker Tailor Java WHY? III]]></title>
            <link>https://medium.com/@somaktukai/tinker-tailor-java-why-iii-f7a8d1e1ff4e?source=rss-58a940293646------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a8d1e1ff4e</guid>
            <category><![CDATA[visualvm]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[profiler]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Somak Dutta]]></dc:creator>
            <pubDate>Sun, 30 Oct 2022 09:38:17 GMT</pubDate>
            <atom:updated>2022-10-30T09:47:35.507Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets observe how we performed method profiling to identify the 20x time difference between multi map and single map approach</p><p><a href="https://medium.com/@somaktukai/tinker-tailor-java-why-27013673b8a8">Root page</a></p><p><a href="https://medium.com/@somaktukai/tinker-tailor-java-why-i-a68061111f1b">Part I</a></p><p><a href="https://medium.com/@somaktukai/tinker-tailor-java-why-ii-8140d79c7be1">Part II</a></p><p>I recently came across a wonderful article that truly explained the concepts of Log Structured Merge Tree(LSM Trees) in the best possible way.</p><p>Credit to this particular site : <a href="https://yetanotherdevblog.com/lsm/">https://yetanotherdevblog.com/lsm/</a></p><p>While reading through it, my habit of tinkering needlessly started rearing its ugly head. So I thought to myself, hey why not! Lets see if we can code this out.</p><p>The first part of this series explains the data structure used and the performance observed when doing some random dropwizard timer metrics. I would recommend reading the first part of this series, if only to understand the data structures being benchmarked.</p><p>The second part of this series demonstrated using JMH to benchmark test runs. Observation was that multimap approach was around 20times faster than single map approach</p><p><em>This really did not make any sense to me, I did expect a bit of performance improvements in multi map but not of this magnitude.</em></p><p><strong>So lets method profile , and identify reason</strong></p><p>Table of Contents</p><p><a href="#82c6"><strong><em>Method Profiling Tool Used</em></strong></a></p><p><a href="#3148"><strong><em>Steps Taken</em></strong></a></p><p><a href="#61c0"><strong><em>Single Map Observations</em></strong></a></p><p><a href="#f7bc"><strong><em>Multi Map Observations</em></strong></a></p><p><a href="#732a"><strong><em>Observations Compared/ Snapshots</em></strong></a></p><p><a href="#cf27"><strong><em>Future Tasks</em></strong></a></p><p><a href="#cdae"><strong><em>References</em></strong></a></p><h3><strong>Method Profiling Tool Used</strong></h3><p>Simple and available tools are the best. Even though there are multiple commercial grade profiles available ( eg jprofiler, yourkit, etc) and they do provide like a 2 week trial period; specific to my use case just using something as simple as Visual VM did the trick.</p><p>The below criteria where used to generate test results:</p><ul><li>Single Map : running 3 benchmarking tests, each with 3 forks. Measurements were taken at 30th, 60th and 90th iteration after warmups of 10 iterations</li><li>Multi Map : running 3 benchmarking tests, each with 3 forks. Measurements were taken at 30th, 60th and 90th iteration after warmups of 10 iterations</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ed93850b3cb38ab8de0db287411ba9/href">https://medium.com/media/93ed93850b3cb38ab8de0db287411ba9/href</a></iframe><h3>Steps Taken</h3><p>While my JMH tests were being executed the following steps were taken:</p><ul><li>open Visual VM</li><li>you would observe JMH main method forking separate processes for executing the tests</li><li>Open any one of them, go to Profiler tab and under CPU settings, put in the class/package name you would like to profile. Eg in my case : com.org.somak.** ( remember ** and * are different things in Visual Vm, and I would let you figure that out. <em>psst! no need to google, just hover over visualvm Profile classes text area</em>)</li><li>Click on CPU to start profiling</li></ul><h3>Single Map Observations</h3><p>What exactly does the method saveData perform:</p><ul><li>adds to an internal concurrent hashmap</li><li>key is equal to tablename and value is a key/value java object being added to TreeMap</li><li>size parameters are checked</li><li>if size parameter is breached, map is flushed to disk using Kryo serialization</li></ul><p>Now that we know the steps that the method takes the following will make sense.</p><p><em>What i expected:</em></p><ul><li>I expected flushToDisk method being called multiple times, since in single map approach we do flush far more frequently than multimap</li><li>I expected flushToDisk method to be the bottleneck</li></ul><p>If you notice the below profiling example, you would notice:</p><ul><li>while flushToDisk method does take a bit of time, the bottleneck is not exactly that</li><li>There is a pesky little put() method that somehow is taking up 90% of the time</li><li>If we expand that particular method, we can see in 2nd image below, a nasty little String.format() method is the real bottleneck</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4T-qvGH8-MkgOjsWmuhFA.png" /><figcaption>I expected flushToDisk to take up time, however it is the add method to map that misbehaves</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCGuRGegyVCNjL9lvy6hFQ.png" /><figcaption>String.format method taking up time</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaaf42788d4fc308ba9ba09ba64d8a24/href">https://medium.com/media/aaaf42788d4fc308ba9ba09ba64d8a24/href</a></iframe><h3>Multi Map Observations</h3><p>What exactly does the method saveData perform:</p><ul><li>adds to an internal concurrent hashmap</li><li>key is equal to tablename and value is a key/value java object being added to TreeMap</li><li>size parameters are checked</li><li>if size parameter is breached, map is flushed to disk using Kryo serialization</li></ul><p>Now that we know the steps that the method takes the following will make sense.</p><p><em>What i expected:</em></p><ul><li>The size of flushed object would be significantly larger compared to single map approach. I expected the majority of time to be spent in flush method. This is also evidenced in the profiling below.</li><li>Additionally, since this performs relatively at 20x throughput compared to single map , I really did not have any profiling expectation</li><li>This was mostly profiled as a control step</li></ul><p>If you notice the below profiling example, you would notice:</p><ul><li>flushtoDisk method does take a longer time to complete compared to single map approach</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvmcO9m3-ec1uIYfq0wcbQ.png" /><figcaption>Observe time to flush</figcaption></figure><h3>Observations Compared/Snapshot</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec05a97080e5178c90fd805d92f035d/href">https://medium.com/media/2ec05a97080e5178c90fd805d92f035d/href</a></iframe><h3>Future Tasks</h3><p>A pretty exciting one at that!!!</p><p>Lets remove the pesky little string.format() method and rerun our tests.</p><p>Byeeee!!</p><h3>References:</h3><ul><li><a href="https://yetanotherdevblog.com/lsm/">https://yetanotherdevblog.com/lsm/</a></li><li><a href="https://github.com/in-tandem/datastore">https://github.com/in-tandem/datastore</a></li><li><a href="https://github.com/openjdk/jmh">https://github.com/openjdk/jmh</a></li><li><a href="https://github.com/melix/jmh-gradle-plugin">https://github.com/melix/jmh-gradle-plugin</a></li><li><a href="https://visualvm.github.io/">https://visualvm.github.io/</a></li></ul><p><em>p.s : i dont believe in censorship. Go for it in the comments box :D</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a8d1e1ff4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>