<?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 Athul A R on Medium]]></title>
        <description><![CDATA[Stories by Athul A R on Medium]]></description>
        <link>https://medium.com/@athul-ar?source=rss-2fa221041436------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GQMiCRsTSi8e9B1s8GwzfQ.jpeg</url>
            <title>Stories by Athul A R on Medium</title>
            <link>https://medium.com/@athul-ar?source=rss-2fa221041436------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:28:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@athul-ar/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[Load balancing & Subsetting]]></title>
            <link>https://medium.com/@athul-ar/load-balancing-subsetting-a6866e5ca19d?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6866e5ca19d</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Tue, 12 May 2026 03:24:49 GMT</pubDate>
            <atom:updated>2026-05-12T03:24:49.248Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This write-up explores the problems of load balancing and sunsetting. It also discusses various approaches one can take for both these problems and how they mirror each other. Ideas and pictures were taken from the paper: <a href="https://cacm.acm.org/practice/reinventing-backend-subsetting-at-google/">Reinventing Backend Subsetting at Google</a>.</blockquote><h3>Load Balancing</h3><p>Load balancing is a fundamental technique in distributed systems that efficiently distributes incoming network traffic across multiple servers or resources. Its primary goal is to optimize resource utilization, maximize throughput etc by preventing any single server from becoming a bottleneck or a single point of failure. Given these many goals and the degrees of freedom amongst many replicas, we have quite a few approaches at trying to achieve a good distribution. Let’s look at them in (roughly) increasing order of complexity. Simpler load balancing approaches often rely on straightforward algorithms that distribute requests which are fairly straightforward to implement but can lead to uneven distribution or skew in various scenarios. By increasing the complexity and potentially adding some overhead, we can achieve a good trade-off of the target feature set.</p><h3>Take 1 — Round Robin</h3><p><strong>Round Robin</strong> is the most basic method, where requests are sequentially distributed to each server in a continuous rotation. If there are n servers, the first request goes to server 1, the second to server 2, and so on, cycling back to 1 at request (n+1). This is simple, but it doesn’t account for server health or capacity, meaning a slow or overloaded server will still receive requests. It can be enhanced using weighted round robin where a weight is assigned to each server based on its capacity and servers with higher weights receive a larger share of the incoming requests. This helps in distributing load more effectively across heterogeneous servers but often requires manual configuration, can’t adapt quickly to changes etc.</p><h3>Take 2 — Dynamic decisions</h3><p>A slightly different approach is to optimise some indicative metric of load. For example, <strong>Least Connections</strong> based load balancing directs new requests to the server with the fewest active connections. It aims to prevent servers from becoming overloaded and maintain a more consistent load across the server pool. This method works well when connections are persistent and vary in duration, but this is more complex and makes potentially bad assumptions like equal capacity for server tasks. On the other spectrum, you can make this decision metric hash-based where the source and destination IP addresses of the client are used to generate a hash value, which then consistently maps the request to a specific server. This works well for maintaining session affinity or caching too. But, the main drawback here is that if a server got added or removed, then the entire mapping changes. Put another way, this rehashing results in a lot of churn in connections.</p><h3>Take 3 — Consistent hashing</h3><p><strong>Consistent hashing</strong> addresses this problem by minimizing the number of keys that need to be remapped when the number of servers (nodes) changes. It works on the principle of a hash ring where hash space is arranged in a circle and server nodes and request keys are both hashed using the same hash function and mapped. That server that responsible for a key will be the first taken clockwise hash. This is essentially the traditional hashing approach with a longer lookup. The advantage we get is minimal remapping. How? — when a server is added or removed, only a few data keys needs to be remapping to maintain the clockwise invariant which is a massive reduction. This can still result in some skew and to reduce it especially in cases of small number of physical servers, each one can be assigned multiple nodes (virtual nodes ) in the ring and reduces impact even more. It can be proved that the solution is optimal, which means that least number of keys need to be remapped to maintain load-balance on an average. Consistent hashing is widely used in distributed caching, distributed hash tables (DHTs), and content delivery networks (CDNs) to ensure scalability and fault tolerance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*2QILiKvJfPxQ7pRaHR4lSw.png" /><figcaption>Consistent hashing</figcaption></figure><h3>Subsetting</h3><p>Subsetting is a related idea to load balancing where the goal is to divide a large dataset into smaller, more manageable subsets for analysis or processing. While load balancing focuses on distributing traffic, subsetting focuses on organizing resources. In <a href="https://cacm.acm.org/practice/reinventing-backend-subsetting-at-google/">Google’s ACM paper on subsetting</a>, the chosen application is assigning frontend tasks to backend tasks. The method of subsetting is the task at hand and the choice depends on the specific application. But, it broadly follows the same increasingly complex approaches in load balancing.</p><h3>Take 1 — Random subsetting</h3><p>The simple starting algorithm is to choose random subsets for each Each frontend task shuffles the list of backend tasks and selects the first k tasks. This is straightforward to implement but doesn’t work well in practice. It interacts poorly with many load-balancing policies primarily as it leads to a non-uniform distribution of connections across backend tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*EswUDDMNSVfZ44lK_F6T6w.png" /></figure><h3>Take 2 — Round Robin</h3><p>We can do round robin subsetting which is actually excellent if just the subsetting is concerned, but it has other practical issues. For example, if you deploy a canary to a backend, it might crash and affect tasks in some frontend tasks disproportionately. Also, if a frontend task fails or is restarted, and then comes back up, it will deterministically be assigned a different subset of backends than it might have had before, leading to connection churn on the backend side.</p><h3>Take 3 — Determinstic subsetting</h3><p>Subset diversity missing in round robin subsetting can be increased by introducing randomness. In practice, this leads to a solution where you shuffle all the backend tasks, assign them to the first few front ends, and then repeat this. This idea along with some round robin management of the left over tasks after a cycle <a href="https://sre.google/sre-book/load-balancing-datacenter/">seemed like a good model at least in Google</a>. But, this faced issues when Autopilot made horizontal resizing of the backend tasks more frequent which means there is a lot of backend connection churn now with this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*m6yEx48lslRY-PoXhVfFnw.png" /></figure><h3>Take 4 — Ringsteady Subsetting</h3><p>The goal is to keep the good things about deterministic subsetting but drastically reduce connection churn. The problem was the connection balance is determined by how evenly spaced the backend tasks are around the circle and they were essentially. The approach Google came up with was to improve on backend tasks getting randomly chosen positions by using a sequence of positions that favors an even distribution: a low-discrepancy sequence. The sequence Google chose is the binary van der Corput sequence,<a href="https://cacm.acm.org/practice/reinventing-backend-subsetting-at-google/#FNH">h</a> which begins (with the addition of 0 as the zeroth element) as 0, ½, ¼, ¾, ⅛, ⅝, ⅜, ⅞.</p><p>Note that this approach works only because the backend tasks are consecutively numbered, so the <em>n</em>th element in the low-discrepancy sequence can be associated with the <em>n</em>th backend task. This means if a backend gets added or removed, the connection churn of the subset is drastically reduced. The figure shows utilisation against #frontend/#backend ratio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*uzXJDx6VwwR-H-JG0tuhKg.png" /></figure><h3>Final take — Rocksteadier Subsetting</h3><p>The last one still had a small pitfall as seen in (c). When Frontend tasks outnumber backend tasks, utilization does not converge toward the ideal. The low-discrepancy sequence results in the positions for frontend and backend tasks not exactly evenly spaced which is bad for scenarios with leftover tasks. You can fight it by eliminating leftovers, and you can do that by scaling frontend or backend tasks. Frontend scaling is not a good idea though since frontend scaling makes the positions of frontend tasks dependent on the frontend size, which introduces a lot of frontend churn. Rocksteadier Subsetting is essentially Ringsteady Subsetting + backend scaling. This seems to be the final frontier, <em>for now.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*pmt_QvJbXTHmlh2EG4buwA.png" /></figure><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*rcJ7KL0vmsnzl2H9Gftr3w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6866e5ca19d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VM Images]]></title>
            <link>https://medium.com/@athul-ar/vm-images-3769bac95297?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/3769bac95297</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[vm]]></category>
            <category><![CDATA[vmware]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Tue, 12 May 2026 03:11:27 GMT</pubDate>
            <atom:updated>2026-05-12T03:11:27.982Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>There are a lot of choice for <strong>image types</strong> when migrating an existing workload to Cloud or doing coursework with the provided VM. This write-up tries to clear up the usual confusion. Also, GCP and Virtualbox are used as comparison for Cloud and desktop virtualisation usecases in the context of this write-up.</blockquote><h3>Images</h3><p>Images refer to disk image formats that encapsulate the entirety or template of an operating system, applications, and data. It is a good mechanism to manage environments whether it be migrated on-prem workloads to Cloud or making sure your homework <em>works</em> on the instructor’s machine. There are a few broad classifications of images.</p><p>The simplest one being raw image, which is the exact sector-by-sector data of the disk, including partition tables, file systems, and all files without compression. The usual formats are img, dd etc. It is useful for analysis and a base for conversion to other types. Virtual box can directly attach these images as virtual hard disks. But, it is not a primary method of importing in GCP.</p><h3>Virtual Disk Image</h3><p>These images are designed specifically for use with virtualization software. There are few options here, each popularized by widely used desktop virtualisation softwares. By extension, these disks are one of the common ways virtual machines are created in Cloud. For instance, <a href="https://cloud.google.com/compute/docs/import/importing-virtual-disks">GCP allows</a> you to importing these virtual disks into Compute Engine and using the resulting image to <a href="https://cloud.google.com/compute/docs/instances/create-start-instance">create virtual machines</a>. Below are the common types you are likely to encounter in the wild. GCP supports <a href="https://cloud.google.com/sdk/gcloud/reference/compute/images/export">all 3</a> discussed below. Virtualbox being a free and open-source software also supports all these image types. There are some interesting properties and features associated with virtual disk images. Most of them support some form of thin provisioning (also called sparse disks) which means the disk file only grows as data is written that helps in saving. The underlying functionality is often via the <a href="https://en.wikipedia.org/wiki/Copy-on-write">copy-on-write</a> model, qcow is infact QEMU copy-on-write. QEMU additionally has support for compression making it more space efficient as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naiw1k1vxrpZElkxfr7inA.png" /><figcaption>Comparison of image types</figcaption></figure><h3>Virtual Appliance Images</h3><p>A <strong>virtual appliance</strong> is a pre-configured <a href="https://en.wikipedia.org/wiki/Virtual_machine_image">virtual machine image</a>, ready to run on a <a href="https://en.wikipedia.org/wiki/Hypervisor">hypervisor</a>. Therefore a virtual Appliance image is not just the disk image but also the VM’s configuration like CPU, RAM etc allowing for easy portability. There are 2 popular formats: Open Virtualization Format (OVF) and Open Virtualization Appliance (OVA).</p><p>OVA is essentially an open standard for packaging VMs. It contains multiple files — an .ovf file which is an XML descriptor of the hardware configuration, an actual disk image discussed in the above section as well as other optional files. This is meant for interoperability which translates to excellent support in Virtualbox for importing OVF appliances. But, GCP doesn’t allow you to directly import an entire OVF package. Instead, we have to import just the packaged disk image to create the VM image and manually use the hardware configuration when creating a VM with the created image. OVA is a single-file tar archive that contains all the files of an OVF package making it essentially a convenience wrapper for OVF. The same principle as OVF applies.</p><h3>Summary: How do I create a VM in GCP?</h3><pre># Prepare Your Image:<br># 1. If you have .raw image, convert it to .tar.qz first.<br># 2. If you have a virtual disk like .vmdk, there is nothing to do.<br># 3. If you have a virtual appliance disk, extract the virtual disk like .vmdk out of it.<br># --&gt; Let&#39;s say the file is my-os.vmdk<br># Upload to Cloud Storage.<br>$ gsutil cp my-os.vmdk gs://my-os-bucket/<br># Create a Custom Image in GCP with relevant Guest OS features.<br>$ gcloud compute images create my-custom-image \<br>    --source-uri gs://your-bucket-name/my-os.vmdk \<br>    --guest-os-features UEFI_COMPATIBLE,VIRTIO_SCSI<br>    <br># Create a VM Instance from the Custom Image.<br>gcloud compute instances create my-vm-instance \<br>    --image my-custom-image \<br>    --zone us-central1-a \<br>    --mach</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3769bac95297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yima: A Continuous Media Server case study]]></title>
            <link>https://medium.com/@athul-ar/yima-a-continuous-media-server-case-study-0da491d92808?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/0da491d92808</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 23:32:00 GMT</pubDate>
            <atom:updated>2025-06-08T23:39:38.440Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This is a summary of <a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=ec8063e8930462b99c07f852acb152e43d56eb32">the original paper</a> done as part of Operating Systems coursework.</blockquote><h3>Goal</h3><ul><li>Continuous Media (CM), such as video, audio, and newer types like haptic data, present significant challenges for storage and network delivery due to their real-time constraints and large object sizes.</li><li>Solutions for handling CM are either low-cost, limited-user systems or expensive, high-end carrier-class systems. Yima, a next-generation prototype aims for a scalable, cost-effective real-time streaming architecture.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t_IihnOrlZ3l3wNm.png" /><figcaption>Why Media servers? (Source: <a href="https://trembit.com/blog/webrtc-media-servers-overview-and-explanation-what-to-choose/">Trembit</a>)</figcaption></figure><h3>Functionalities</h3><ol><li>Complete Distribution: All nodes run identical software with no single points of failure.</li><li>Efficient Online Scalability: Disks can be added or removed without service interruption.</li><li>Stream Synchronization: Capable of synchronizing multiple audio/video streams within one frame time.</li><li>Advanced Network Protocols: Incorporates selective retransmission and multithreshold buffering for Variable Bit Rate (VBR) media.</li></ol><h3>System Architecture</h3><ul><li>Yima runs a cluster of PCs running Linux, interconnected via Fast or Gigabit Ethernet, with high-performance SCSI disks for storage.</li><li>The network design is IP-based. This helps make it cost effective.</li><li>Yima’s clients just need to have the Yima Presentation Player software which supports various plug-in decoders for different media types.</li></ul><h3>Challenges</h3><p>1. Data Placement and Scheduling:</p><ul><li>Yima utilizes a pseudorandom data placement strategy across all disks in the cluster instead of the traditional round-robin placement or pure random placement.</li><li>Pseudo-random placement simplifies scheduler design, achieves good load balancing across disks and minimizes metadata overhead since schedulers only need to store a single seed value per file to regenerate block locations.</li><li>This also has the benefit of pure random placement where redistribution is more efficient when the system scales.</li></ul><p>2. Scalability, Heterogeneity, and Fault Resilience:</p><ul><li>The multinode architecture inherently supports scalability by allowing easy addition of new nodes.</li><li>To handle disk failures and diverese disk capabilities, disk merging is used wherea virtual layer of uniform logical disks are created over physical disks and exposed to the upper layers.</li><li>This simplifies data placement, scheduling and implementing fault tolerance.</li></ul><p>3. Data Reorganization for Scaling:</p><ul><li>When nodes or disks are added/removed, data has to be reorganized to maintain load balance.</li><li>Pseudorandom placement is used by Yima as explained earlier and it significantly reduces the overhead of reorganization since only a subset might need relocation compared to Round Robin.</li><li>Yima uses the Scaddar algorithm, based on composing random functions, to efficiently compute new block locations with minimal data movement, allowing disks to be scaled even while the server is online.</li></ul><h3>Server Architecture</h3><p>Yima evolved through two main architectural designs with different priorities. Yima can run in either of these <em>modes</em>.</p><ol><li>Yima-1 (Master-Slave):</li></ol><ul><li>In this initial design, server software has 2 main components — DFS and Media streaming server. The clients interact with a designated master node for its entire session.</li><li>The master node runs both the components and brokers requests to slave nodes which primarily handle file I/O (DFS).</li><li>For VBR media, Yima-1 used a simple pause-resume flow control based on client buffer levels.</li><li>While functional, this design suffered from master node bottlenecks and significant internode data traffic as data often flow from slaves via master to the client.</li></ul><p>2. Yima-2 (Bipartite):</p><ul><li>To overcome Yima-1’s limitations, Yima-2 adopted a more decentralized, bipartite model. Bipartite refers to the system having 2 groups — server and client.</li><li>While a client still has to connect to a node for RTSP control commands, the scheduling and RTP data delivery are parallelized within the group.</li><li>Each node directly retrieves, schedules, and sends its local data blocks to the requesting client. This drastically reduces internode traffic and eliminates the master bottleneck.</li><li>But, Yima-2 required modifications to handle clients receiving data from multiple sources and implemented a distributed scheduler and flow-control mechanisms (for VBR) to avoid client overflow/starvation scenarios.</li></ul><h3>Client Architecture</h3><p>1. Buffer Management and Flow Control:</p><ul><li>The Yima Presentation Player uses a circular buffer with multiple watermarks to support VBR.</li><li>It supports both the simple pause-resume method (master server transmission based on overflow/underflow, Yima-1) and the finer-grained Δp control (Yima-2).</li><li>So, with both Yima-1 and Yima-2, the client is in control. It monitors buffer levels against watermarks and sends small speedup or slowdown commands to the server(s) for smoother delivery.</li></ul><p>2. Media Support and Synchronization:</p><ul><li>Yima supports various media types using software (e.g., DivX/MPEG-4) and hardware (e.g., MPEG-2) decoders. Streaming high-definition content was achieved using both optimized software decoding and dedicated hardware.</li><li>A key capability is the synchronization of multiple independent streams. Using retrieval scheduling, and hardware level genlock signals with compatible decoders, Yima can achieve frame-accurate playback synchronization.</li></ul><p>3. Networking: RTP/UDP and Selective Retransmission:</p><ul><li>Yima uses the standard RTP/UDP protocols for media delivery. To mitigate packet loss inherent in UDP (as opposed to reliable delivery in TCP), a selective retransmission protocol is implemented.</li><li>The server attempts at most one retransmission per lost packet, only if it can arrive in time. In Yima-2, where it is more challenging as packets for a single stream come from multiple nodes, the client efficiently determines which node to send the retransmission request avoiding the overhead of broadcasts.</li></ul><h3>Test Results and Conclusion</h3><ul><li>As expected, experiments showed Yima-2 achieved near-linear scalability with increasing nodes, outperforming Yima-1 which leveled off due to internode traffic.</li><li>Successful streaming of MPEG-4 over a residential ADSL connection demonstrated the effectiveness of rate control and retransmission protocols, achieving good quality despite low bandwidth and some packet loss. But, it was also capable ofHigh-bandwidth, multi-stream synchronized playback.</li><li>Future work includes exploring resource management across geographically distributed Yima clusters and supporting additional immersive media data types.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0da491d92808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microkernel]]></title>
            <link>https://medium.com/@athul-ar/microkernel-acdc2525c0a0?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/acdc2525c0a0</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[micro-kernel]]></category>
            <category><![CDATA[fuchsia-os]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 05:05:37 GMT</pubDate>
            <atom:updated>2025-02-23T14:27:41.700Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Partially from the <a href="https://omscs.gatech.edu/cs-6210-advanced-operating-systems">Advanced Operating Systems</a> course, and partially from a discussion with a teammate. This write-up covers what microkernel is, new and old examples, why does it have a bad reputation and why it is mostly unwarranted.</blockquote><h3>What is it?</h3><ul><li>A microkernel is a minimal operating system kernel that provides only the essential services. It aims to achieve high reliability and flexibility by separating core system services from user-level services.</li><li>It only provides the most basic functionalities such as Address space management. Thread management and Inter-process communication (IPC). Applications, drivers, protocol stacks and filesystems run outside the kernel in their address spaces.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*40GhIFU6TI-Hjytu7jLobQ.png" /><figcaption><em>Typical trade-offs involved when building Operating Systems (AOS Gatech)</em></figcaption></figure><ul><li>While a microkernel architecture has a light core, a monolith architecture like Linux is the opposite. Many device drivers are included in the kernel itself reducing the system function overhead and improved efficiency at the expense of flexibility. DOS is at the other extreme where OS and user level processes are in the same protection domain giving much less safety. But, microkernels can also be performant despite having a potential for performance loss, the next section a case in point if done well.</li></ul><h3>Fuschia</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Wm1MtMuFcJLrnqyn4E6n9Q.png" /><figcaption>Fuschia — Zircon and System services built on top of it (from official documentation)</figcaption></figure><ul><li><a href="https://fuchsia.dev/">Fuchsia</a> is a modern open source operating system by Google that’s simple, secure and performant. It happens to use a microkernel called Zircon.</li><li>Fuchsia employs a capabilities-based security model. This means that processes are granted specific permissions to access resources, rather than relying on traditional user-based permissions similar to <a href="https://medium.com/@athul-ar/access-control-systems-fc3049fa0e13">SELinux</a>.</li></ul><h3>Why was it not adopted?</h3><p>Even today, the dominant style is monolithic. The common albeit a bit flawed rationale is that the microkernel will not be performant. Why? — if the kernel only supports basic functionalities and there is no compromise in safety, then even simple actions requires multiple jumps. For example: if the application has to write to a file, the minimal jumps needed are application → microkernel → file system → microkernel → application. That’s a lot of jumps and there is a <strong>potential</strong> for performance loss. The key problems are as follows:</p><ol><li>Firstly, there is this explicit cost of switching the address space, from one hardware address space to another hardware address space.</li><li>There are also implicit costs involved in this border crossing due to change in locality. The memory hierarchy, the caches in particular may not be <a href="https://stackoverflow.com/questions/22756092/what-does-it-mean-by-cold-cache-and-warm-cache-concept">warm</a>. A change in locality is another important determinant of performance and it can adversely effect the performance.</li><li>Finally, when going across address spaces, there may be a need to copy from user space to system space which are directly avoided in monolithic design.</li></ol><p>The earliest reference microkernel is <a href="https://en.wikipedia.org/wiki/Mach_(kernel">Mach</a>, which is much slower compared to monolithic kernels. This was attributed to be due to the fundamental principle behind microkernels, and therefore much of the focus in the 1990s was given to expanding monolithic kernel principles to achieve extensibility, notably <a href="https://en.wikipedia.org/wiki/Exokernel">exokernel</a> and <a href="https://en.wikipedia.org/wiki/SPIN_(operating_system">SPIN</a>. But, it turns out that Mach was not performant mostly due to a completely different reason.</p><h3>L3</h3><p><a href="https://en.wikipedia.org/wiki/Jochen_Liedtke">Jochen Liedtke</a> set out to prove that with careful attention to performance and machine-specific design, microkernels could be performant as well. And he did it by <strong>proof of construction</strong>. We shall focus on how the 3 potential problems discussed above are mitigated.</p><ol><li>Address space switches: the key idea is that processes and services have to be in their own protection domain, yes, but not necessarily in distinct hardware address spaces. Liedtke’s suggestion is that take advantage of whatever the architecture offers you for protection and avoid address space switches.<br>(a) If architecture supports address space tags in addition to the tag for disambiguating one virtual address from another virtual address in TLB, then you don’t have to flush the TLB.<br>(b) If the architecture offer segment registers that specify the range of virtual addresses that can be legally accessed by the currently running process, it can define protection domains.</li><li>The implicit costs are a bit more tricky to analyse. Essentially, there are 2 cases. If the processes in a group aren’t huge, using architecture specific techniques will avoid the need for TLB flushes and therefore, these costs can be avoided to a large extent. But, if the processes are big that it needs large address space, microkernels can’t do much. But, here implicit costs such as cold caches are much higher than address space switch costs, and it can’t be avoided in monolithic either. So, it is not really a downside for microkernel.</li><li>As microkernel crosses multiple protection domains (now we know it’s not always address spaces), there <em>can</em> be multiple copies involved which is not good. But, this can be optimised by following a well-designed thin IPC layer such as light RPC (LRPC). What does LRPC client and server do differently? — Well, it offloads the heavier step of memory allocation to an initial authentication step where client and server establish connection. What that achieves is a common memory region where client can write to, and be blocked until server uses it, does the job and returns effectively avoiding copies. This first step is heavy, but it only needs to be done the first time. All subsequent communication can reuse the region (regions if concurrent connection limit is more than 1) making the common case optimal.</li></ol><p>Hence, by proof of construction, microkernel is shown to be a performant system. The caveat and the reason why Mach is slower is the same. Note that L3 makes <em>machine-specific optimisation</em> and is therefore not portable. Mach, on the other hand, was very much focused on portability in addition to extensibility. So, Mach has an architecture specific and an independent part that results in significant code bloat hampering performance. This unfortunately gave a bad press for microkernel based design.</p><h3>Conclusion</h3><p>In conclusion, there are 4 degrees of freedom when you consider portability. And microkernels can achieve arguably the 3 more important ones with the right set of kernel abstractions and processor-specific implementation. With that as the foundation, efficient processor-independent abstractions can be built at the upper layers as newer microkernels such as Fuchsia has shown. Microkernel approach is therefore a viable alternative of building OS if done well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acdc2525c0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Martingale]]></title>
            <link>https://medium.com/@athul-ar/martingale-7d7c1104ee4c?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7c1104ee4c</guid>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[martingale-strategy]]></category>
            <category><![CDATA[stochastic-process]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 04:51:25 GMT</pubDate>
            <atom:updated>2025-02-23T04:53:11.290Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This is a short exploration of Martingale and its properties while looking at multiple phenomena that shows this behavior like Brownian motion and gambling.</blockquote><h3>Introduction</h3><p>Martingales are a class of stochastic processes that have found wide applications in various fields, including probability theory, statistics, and mathematical finance. A martingale is a sequence of random variables X₀, X₁, X₂… such that for any time n:</p><ol><li>The expected value of Xₙ is finite, i.e., E(|Xₙ|) &lt; ∞</li><li>The conditional expectation of the next value , given the current and past values X₀, X₁, X₂…Xₙ is equal to the current value Xₙ<em>, i.e E(X</em>ₙ₊₁|X₀, X₁, X₂…Xₙ) = Xₙ.</li></ol><h3>Interpretation &amp; Properties</h3><p>The martingale property can be interpreted as a <strong>fair game</strong> condition. Given all the information up to the present, the expected value of the process at the next time step is equal to its current value. This implies that, on average, there is no tendency for the process to increase or decrease.</p><p>A classic albeit academic example is a random walk or a drunkard’s walk. The sequence of drunkard’s steps is a sequence independent and identically distributed random variables Z₀, Z₁, Z₂… where each Zᵢ takes the values +1 or -1 with equal probability. The drunkard’s current position Xₙ = Z₀ + Z₁ + Z₂ + Zₙ is a martingale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*M49M9D2UoXbjwDKuszAQoA.png" /></figure><p>Some interesting properties are:</p><ol><li><strong>Boundedness:</strong> If a martingale is bounded, meaning that there exists a constant M such that |Xₙ| ≤ M for all n, then the martingale converges almost surely.</li><li><strong>Optional Stopping Theorem:</strong> Under certain conditions, the expected value of a martingale at a stopping time is equal to its initial value. This theorem has important applications in finance and gambling theory.</li></ol><h3>Fun example: Gambling</h3><p><strong>Accumulated Wealth in a Fair Game:</strong> Suppose you start with an initial amount of money and you play a fair game, where you have an equal chance of winning or losing a fixed amount. If you repeatedly play such that you double the bet after every loss, your accumulated wealth after each round forms a martingale.</p><p>Say the gambler starts with $1, then loses and doubles the bet for n times and wins the round n+1. As shown in the equation, the profit is 1 which is independent of N. That means the gambler recovers all his losses and makes a profit as soon as he wins 1 spin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*TSFdXo0GfJdAOZ_XwRnNOw.png" /></figure><p>The rationale is that eventually you will win, and when you do all losses will be recovered in addition to a profit. While the theory is mathematically sound, it is a highly risky strategy due to a couple of reasons. Firstly, the potential losses can quickly escalate. Secondly, the strategy relies on unlimited bankroll and no betting limits both of which are not seen in real-world gambling. With these constraints in place, it is often not as good a strategy as demonstrated in the experiments.</p><h3>Serious example: Brownian motion</h3><p>Imagine a tiny particle suspended in a liquid. It constantly gets bumped around by the liquid molecules, resulting in a random, jittery movement. Brownian motion is this random motion of particles suspended in a medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*oedWOfbfjXghR-TGumlbiw.png" /><figcaption>Journey of a particle suspended in a liquid</figcaption></figure><p>The Brownian motion can be modeled by a random walk and equivalently, a martingale. An intuitive picture is Brownian motion has no <em>memory</em> due to independent increments. So, past movements don’t help predict future ones. This <a href="https://en.wikipedia.org/wiki/Brownian_motion">Wikipedia</a> image shows a representative journey of such a tiny particle.</p><h3>Tailpiece — Submartingale &amp; Doob’s Martingale Inequalities</h3><p>A discrete-time <strong>submartingale</strong> is a sequence of <a href="https://en.wikipedia.org/wiki/Integrable_function">integrable</a> random variables satisfying X₀, X₁, X₂…<em> such that E(X</em>ₙ₊₁|X₀, X₁, X₂…Xₙ) ≥ Xₙ. A good model is a bacteria colony growing in a petri dish. While the number of bacteria might fluctuate due to resource availability or other factors, if the colony is generally expected to grow, the number of bacteria at time t can be modeled as a submartingale. The expected future number of bacteria, given the current count, would be greater than or equal to the current count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*86g7cGFlHXrpUvr3B0dShg.png" /></figure><blockquote>An interesting result is Doob’s inequality which gives a bound on the probability that a <a href="https://en.wikipedia.org/wiki/Submartingale">submartingale</a> exceeds any given value over a given interval of time. Take the model of the bacteria colony. We expect the colony to grow, but the actual number fluctuates due to various factors and has an <em>expected maximum</em> size. Alternatively, the colony is unlikely to get much larger than <em>some</em> value. And that value for those interested can be viewed by the above equation which shows how probability is extremely less with large bounds.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7c1104ee4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Control Systems]]></title>
            <link>https://medium.com/@athul-ar/access-control-systems-fc3049fa0e13?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3049fa0e13</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[iam-policy]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 00:42:51 GMT</pubDate>
            <atom:updated>2025-02-23T05:25:08.249Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This is an attempt to understand the need for and context behind <a href="https://github.com/SELinuxProject/selinux">SELinux</a> and compare with similar ideas in the software world. Also, the way different approaches are presented is not the only way to do it, just something that made sense to me.</blockquote><h3>What is Access Control?</h3><p><strong>Access control</strong> is a data security process to manage who is authorized to access resources. It is an unavoidable piece of application security and therefore important to understand for software engineers. There are typically 3 facets of access control:</p><ul><li>Authentication: check if you are the one who say you are. Common mechanisms include OAuth (an API mechanism), LDAP (vendor neutral application mechanism) etc. This is not the major focus of this talk.</li><li>Authorization: check if you are allowed to do a specific thing. We <strong>focus</strong> on this facet in this write-up.</li><li>Audit: add a data entry with your identity and action for later analysis. In the rest of this discussion, we don’t talk much about this.</li></ul><h3>Types</h3><p>A question to clarify first is who controls access to a specific resource. There are 2 options (<a href="https://www.zuar.com/blog/discretionary-access-control-vs-mandatory-access-control">more details including pros/cons</a>):</p><ol><li>Owner of the resource. This approach is called discretionary access control. It is not very restrictive as it works based on a person’s own discretion and allows the system owner or administrator complete control over who has access permissions throughout the security system.</li><li>System or the administrator. This approach is called mandatory access control. This is very stringent as it allows only the system owner or administrator to control and manage the system and access points. In addition, the administrator can only tweak things laid out by the system’s parameters.</li></ol><p>The next question to keep in mind is how we manage the linkage among the plethora of users and resources. There are a few options again, 2 important ones are discussed here (<a href="https://www.tenfold-security.com/en/wiki/access-control-models">more details including pros/cons</a>):</p><ol><li>Role based access control (RBAC) — here users are grouped into roles and permissions are given only to users. It is an automatable approach because we can leverage the similarities in accesses needed for users. It is much more of a static system.</li><li>Attribute based access control — here the decision metric is attributes of users and data. It is also automatable, but requires a lot of details to get it right safely. It can be viewed as a very dynamic system.</li></ol><p>Now, these 2 are not strictly orthogonal, but it was a helpful way for me to think about what actual systems do. Implementation often use a mix of these approaches to ensure cybersecurity principles such as principle of least privilege (PoLP).</p><h3>Examples</h3><h4>Traditional Linux Access control</h4><p>It is definitely a discretionary access control mechanism where the owner of the resource can give anybody permissions to do anything with the resource. It is vaguely role based since groups can be assigned permissions, but that’s about it in the usual implementations. It can be enhanced using frameworks such as PAM, PolicyKit and SELinux.</p><h4><a href="https://cloud.google.com/iam/docs/overview">IAM in GCP</a></h4><p>Identity and access management (IAM) is a centralized and consistent way to manage user identities. It has a lot of attributes of a role-based access control since there are clear notions of roles, permissions and users. But, <a href="https://cloud.google.com/iam/docs/conditions-overview">IAM Conditions</a> gives it the facilities of an attribute based access control system. It is more mandatory than discretionary though since owners, though exists as a concept, are at project level and owners can’t really assign permissions without any care in the world. In short, IAM has way too many features to be called strictly one type (<a href="https://www.reddit.com/r/googlecloud/comments/m5v6n0/access_control_model_in_gcp/">an interesting Reddit discussion</a>).</p><h4><a href="https://github.com/SELinuxProject/selinux">SELinux</a></h4><p>It is most definitely a mandatory access control since users can’t disable it. This means that even if your process runs as root, SELinux will be in effect, and may block you from doing stuff. It also has properties of RBAC since SELinux policies make clear use of roles and actions each role can do with each type based on the resource’s security context.</p><h3>A bit more about SELinux</h3><p><strong>S</strong>ecurity-<strong>E</strong>nhanced <strong>Linux</strong> is a set of kernel-level security features in the Linux operating system, provides more fine-grained access control models for resources. It was originally developed by National Security Agency (NSA) as a series of patches to the Linux kernel using Linux Security Modules (LSM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*FX_wryc-yCV1asp0r1Rwtw.png" /></figure><ul><li>This is one of the most common ways of avoiding limitations of discretionary access control in a typical Linux system. For example, RedHat and Rocky Linux install SELinux by default.</li><li>Resources in the early point is meant in the broad sense of the word: files, processes, network sockets, and more. Every resource gets a SELinux security context in the form of user:role:type:range. Files have extended attributes (run ls -Z). Others have their context in the kernel like users, processes and network sockets.</li><li>A user is mapped to a SELinux user, which defines the maximum clearance of that user. The SELinux user is allowed one or more roles. Types are the most important part of a context as all rules are based on types.</li><li>The range field of a context is an advanced setting that assigns a range of sensitivities. It is used to implement fancier security structures such as Multi-Level Security (MLS) which are irrelevant for most SELinux usecases.</li><li>Security policy consists of numerous set of rules. A simple example of a rule is allow init_t user_home_t:file read;. This means that processes with security context init_t are allowed to read files that have the type user_home_t. Similarly, to allow group admins to grant permissions to passwd files, use allow group_admins:file { read write execute } /etc/passwd;.</li><li>Users vs Processes is an interesting idea in the context of SELinux. One way to think about it is: where the Unix file permissions protect users’ and the system files from modification by unintended users, SELinux type enforcing protects resources from modification or usage by unintended processes. But, SELinux can control the permissions granted to users or groups as well as manage the privileges and restrictions of individual processes. Eg: alice has permissions to read files in the /home/alice directory. When alice starts a text editor process, that process will inherit her permissions and can typically access those files. However, SELinux can restrict the process from accessing resources, even if alice has permissions to do so.</li><li>Reference: <a href="https://github.blog/developer-skills/programming-languages-and-frameworks/introduction-to-selinux/">an in-depth comparison</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3049fa0e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approaching string search functionally]]></title>
            <link>https://medium.com/@athul-ar/approaching-string-search-functionally-231853012513?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/231853012513</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dsa-training]]></category>
            <category><![CDATA[string-search]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 03:45:02 GMT</pubDate>
            <atom:updated>2024-08-19T14:28:54.942Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This write-up is an attempt to understand <a href="https://www.cambridge.org/core/journals/journal-of-functional-programming/article/knuthmorrispratt-illustrated/8EFA77D663D585B68630E372BCE1EBA4">Knuth–Morris–Pratt illustrated</a> published in the journal of functional programming. The paper uses Haskell, but my toy implementation is in Go which is not as neat but still illuminating.</blockquote><h3>What is string search problem?</h3><ul><li>The fundamental string searching problem is defined as follows: given two strings — a text and a pattern, determine whether the pattern appears in the text.</li><li>The problem is also known as the <em>needle in a haystack problem</em>.</li><li>The naive implementation will be a O(mn) time complexity solution where m is the length of text and n is the length of the pattern. But, the most optimal solution is the Knuth–Morris–Pratt (KMP) algorithm which does it in O(m+n) time complexity.</li><li>But, it is notoriously difficult to understand due to obscure explanations and confusing index arithmetic. The paper uses Haskell to build KMP in an elegant manner.</li><li>The below write-up uses Go which doesn’t have Haskell’s lazy semantics to explain the above paper which incrementally improves the naive solution to reach KMP.</li><li>For the below discussion, consider text = ammamaa and pattern = mama.</li></ul><h3>1. Horizontal Naive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44SGB6e6ikOi4rglJ0y4Hg.png" /><figcaption>Horizontal scanning of the text for pattern</figcaption></figure><p>Match the pattern at every position in the text. Think of it as going through the text horizontally (<a href="https://github.com/0neir0s/kmp-go/blob/main/horizontal_naive.go">full implementation</a>).</p><p>Each row corresponds to a new starting position in the text. The third row matches fully, so the search is successful.</p><p>We implement the helper functions in a nested manner to match the Haskell code. The functions of interest are:</p><ol><li>scanl - it returns a list of accumulators given a step function, an acc (accumulator) and a slice (stream of values).</li><li>The only functions that changes in the later approaches are step function accepts the current acc and current x (value in the stream) to return the next accumulator, init value of the accumulator and done which checks for match in every iteration.</li></ol><pre>func horizontal(pattern, text string) bool {<br><br> var any func(func(string) bool, []string) bool<br> any = func(done func(string) bool, accs []string) bool {<br>  if len(accs) == 0 {<br>   return false<br>  }<br>  acc, tail := accs[0], accs[1:]<br>  return done(acc) || any(done, tail)<br> }<br> var scanl func(func(string, string) string, string, []string) []string<br> scanl = func(step func(string, string) string, acc string, slice []string) []string {<br>  if len(slice) == 0 {<br>   return []string{acc}<br>  }<br>  x, xt := slice[0], slice[1:]<br>  return append([]string{acc}, scanl(step, step(acc, x), xt)...)<br> }<br> init := text<br> step := func(acc string, _ string) string {<br>  return acc[1:]<br> }<br> done := func(acc string) bool {<br>  return strings.HasPrefix(acc, pattern)<br> }<br> return any(done, scanl(step, init, strings.Split(text, &quot;&quot;)))<br>}</pre><h3>2. Vertical Naive with Set</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1i4XwWhjPeS5Zt3V7x0-A.png" /><figcaption>Vertical scanning of text results in a list of sets to evaluate matches</figcaption></figure><p>We look at the same problem vertically here. Each column is a set of pattern suffixes, all of which are candidates for a match. Calculating the next column involves three steps (<a href="https://github.com/0neir0s/kmp-go/blob/main/vertical_set.go">full implementation</a>):</p><ol><li>Remove suffixes that do not match the current position in the text. These suffixes are failed candidates.</li><li>Take the tail of those that do. These suffixes remain candidates.</li><li>Add the pattern itself, corresponding to the diagonal line of mama. Doing so starts a new candidate at each position.</li></ol><p>The accumulator is a set of all candidates. Go doesn’t have sets. So, a rough substitute is map[string]bool.</p><p>The functions step, init and done are updated to match this reoriented way of looking at the problem.</p><pre>func verticalSet(pattern, text string) bool {<br> var any func(func(map[string]bool) bool, []map[string]bool) bool<br> any = func(done func(map[string]bool) bool, accs []map[string]bool) bool {<br>  if len(accs) == 0 {<br>   return false<br>  }<br>  acc, tail := accs[0], accs[1:]<br>  return done(acc) || any(done, tail)<br> }<br><br> var scanl func(func(map[string]bool, string) map[string]bool, map[string]bool, []string) []map[string]bool<br> scanl = func(step func(map[string]bool, string) map[string]bool, acc map[string]bool, slice []string) []map[string]bool {<br>  if len(slice) == 0 {<br>   return []map[string]bool{acc}<br>  }<br>  x, xt := slice[0], slice[1:]<br>  return append([]map[string]bool{acc}, scanl(step, step(acc, x), xt)...)<br> }<br> init := map[string]bool{pattern: true}<br> step := func(acc map[string]bool, x string) map[string]bool {<br>  candidates := make(map[string]bool)<br>  for c := range acc {<br>   if strings.HasPrefix(c, x) {<br>    candidates[c[1:]] = true<br>   }<br>  }<br>  return union(init, candidates)<br> }<br> done := func(acc map[string]bool) bool {<br>  _, ok := acc[&quot;&quot;]<br>  return ok<br> }<br> return any(done, scanl(step, init, strings.Split(text, &quot;&quot;)))<br>}</pre><h3>3. Vertical Naive with List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_bu4RqjvEO1PxgDrgzEzg.png" /><figcaption>Do we really need sets? Can’t we smartly construct such that list suffices?</figcaption></figure><ul><li>Using a set to represent the accumulator while intuitive is unnecessary. It is not very efficient as multiple traversals are needed at every iteration and done function is not a constant time operation.</li><li>Looking at the condensed visualisation of the previous approach, we realise we don’t need sets. We can make sure the first element of the list is the top of the column, so it will be sorted and there done will be a constant time operation.</li><li>The only noteworthy change in implementation is that step becomes recursive.</li></ul><pre>func verticalList(pattern, text string) bool {<br> var any func(func([]string) bool, [][]string) bool<br> any = func(done func([]string) bool, accs [][]string) bool {<br>  fmt.Println(accs)<br>  if len(accs) == 0 {<br>   return false<br>  }<br>  acc, tail := accs[0], accs[1:]<br>  return done(acc) || any(done, tail)<br> }<br><br> var scanl func(func([]string, string) []string, []string, []string) [][]string<br> scanl = func(step func([]string, string) []string, acc []string, slice []string) [][]string {<br>  if len(slice) == 0 {<br>   return [][]string{acc}<br>  }<br>  x, xt := slice[0], slice[1:]<br>  return append([][]string{acc}, scanl(step, step(acc, x), xt)...)<br> }<br> init := []string{pattern}<br><br> check := func(candidate, x string) bool {<br>  if len(candidate) == 0 {<br>   return false<br>  }<br>  return strings.HasPrefix(candidate, x)<br> }<br><br> var step func([]string, string) []string<br> step = func(acc []string, x string) []string {<br>  if len(acc) == 0 {<br>   return init<br>  }<br>  candidate := acc[0]<br>  if check(candidate, x) {<br>   return append([]string{candidate[1:]}, step(acc[1:], x)...)<br>  }<br>  return step(acc[1:], x)<br> }<br><br> done := func(acc []string) bool {<br>  if len(acc) == 0 {<br>   return false<br>  }<br>  return acc[0] == &quot;&quot;<br> }<br> return any(done, scanl(step, init, strings.Split(text, &quot;&quot;)))<br>}</pre><h3>4. Morris-Pratt Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhqWisLxHNQI25v_sBHwMQ.png" /><figcaption>Can’t the above list of suffix lists be visualized as a graph?</figcaption></figure><p>There is yet more structure that can be exploited. In particular, two key properties unlock the secret to KMP:</p><ol><li>For each pattern suffix, there is only <em>one</em> column “shape” where that suffix is top.</li><li>The rest field of any column is a <em>prior</em> column.</li></ol><p>With these 2 insights, we can convert the above diagram to a graph.</p><p>How is this a linear algorithm? Because step traverses this graph instead of recomputing successors across the entirety of the text.</p><p>Each node would have a next and a rest (back-edge) fields.</p><p>The main part would be constructing this graph (make). This personally seemed very tricky to understand without a functional background. The init value is the entire graph which is the result of make on the entire pattern. But, make needs step function to figure out what’s next. And finally, step has init as the base condition.</p><p>For this cycle to work, we need lazy evaluation. In Haskell, laziness comes by default resulting in a prettier code. But, in Go, we need an indirection of making next a closure (an invocable) to introduce laziness.</p><pre>func morris_pratt(pattern, text string) bool {<br><br> var step func(*tree, string) *tree<br><br> var make func([]string, *tree) *tree<br> make = func(slice []string, partial *tree) *tree {<br>  if len(slice) == 0 {<br>   return &amp;tree{top: &quot;&quot;, next: func() *tree { return nil }, rest: partial}<br>  }<br>  return &amp;tree{top: slice[0], next: func() *tree { return make(slice[1:], step(partial, slice[0])) }, rest: partial}<br> }<br><br> var any func(func(*tree) bool, []*tree) bool<br> any = func(done func(*tree) bool, accs []*tree) bool {<br>  if len(accs) == 0 {<br>   return false<br>  }<br>  acc, tail := accs[0], accs[1:]<br>  return done(acc) || any(done, tail)<br> }<br><br> var scanl func(func(*tree, string) *tree, *tree, []string) []*tree<br> scanl = func(step func(*tree, string) *tree, acc *tree, slice []string) []*tree {<br>  if len(slice) == 0 {<br>   return []*tree{acc}<br>  }<br>  x, xt := slice[0], slice[1:]<br>  return append([]*tree{acc}, scanl(step, step(acc, x), xt)...)<br> }<br><br> init := make(strings.Split(pattern, &quot;&quot;), nil)<br><br> check := func(candidate *tree, x string) bool {<br>  if candidate == nil {<br>   return false<br>  }<br>  return strings.HasPrefix(candidate.top, x)<br> }<br><br> step = func(acc *tree, x string) *tree {<br>  if acc == nil {<br>   return init<br>  }<br>  if check(acc, x) {<br>   return acc.next()<br>  }<br>  return step(acc.rest, x)<br> }<br><br> done := func(acc *tree) bool {<br>  if acc == nil {<br>   return false<br>  }<br>  return acc.top == &quot;&quot;<br> }<br><br> return any(done, scanl(step, init, strings.Split(text, &quot;&quot;)))<br>}</pre><h3>5. Knuth-Morris-Pratt Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3akx8JimAtDnGvUVo-tSw.png" /><figcaption>Can we make step non-recursive? Look at the structure of pattern again.</figcaption></figure><ul><li>This is a neat optimisation over the MP algorithm. Look at the above picture: Suppose the current accumulator is the fourth column (where the top field is a) and the input character is m. That is a mismatch, so MP goes back two columns. That is also a mismatch, so it goes back to the first column.</li><li>Observation: a mismatch at column a always skips over column ama because the top values of the two columns start with the same character.</li><li>This primarily involves making sure rest is always the best column by doing the additional check.</li></ul><pre>func knuth_morris_pratt(pattern, text string) bool {<br><br> var step func(*tree, string) *tree<br><br> check := func(candidate *tree, x string) bool {<br>  if candidate == nil {<br>   return false<br>  }<br>  return strings.HasPrefix(candidate.top, x)<br> }<br><br> var make func([]string, *tree) *tree<br> make = func(slice []string, partial *tree) *tree {<br>  if len(slice) == 0 {<br>   return &amp;tree{top: &quot;&quot;, next: func() *tree { return nil }, rest: partial}<br>  }<br>  n := func() *tree { return make(slice[1:], step(partial, slice[0])) }<br>  var r_star *tree<br>  if check(partial, slice[0]) {<br>   r_star = partial.rest<br>  } else {<br>   r_star = partial<br>  }<br>  return &amp;tree{top: slice[0], next: n, rest: r_star}<br> }<br><br> var any func(func(*tree) bool, []*tree) bool<br> any = func(done func(*tree) bool, accs []*tree) bool {<br>  if len(accs) == 0 {<br>   return false<br>  }<br>  acc, tail := accs[0], accs[1:]<br>  return done(acc) || any(done, tail)<br> }<br><br> var scanl func(func(*tree, string) *tree, *tree, []string) []*tree<br> scanl = func(step func(*tree, string) *tree, acc *tree, slice []string) []*tree {<br>  if len(slice) == 0 {<br>   return []*tree{acc}<br>  }<br>  x, xt := slice[0], slice[1:]<br>  return append([]*tree{acc}, scanl(step, step(acc, x), xt)...)<br> }<br><br> init := make(strings.Split(pattern, &quot;&quot;), nil)<br><br> step = func(acc *tree, x string) *tree {<br>  if acc == nil {<br>   return init<br>  }<br>  if check(acc, x) {<br>   return acc.next()<br>  }<br>  return step(acc.rest, x)<br> }<br><br> done := func(acc *tree) bool {<br>  if acc == nil {<br>   return false<br>  }<br>  return acc.top == &quot;&quot;<br> }<br><br> return any(done, scanl(step, init, strings.Split(text, &quot;&quot;)))<br>}</pre><h3>Conclusion</h3><ul><li>Naive string search works row-by-row.</li><li>Going column-by-column yields a new algorithm, but it is still not linear time.</li><li>MP takes advantage of the underlying structure of columns, representing them as a cyclic graph.</li><li>KMP refines this algorithm further, skipping over columns that are guaranteed to fail on a mismatched character.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=231853012513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolation in Databases]]></title>
            <link>https://medium.com/@athul-ar/isolation-in-databases-3e4968990a7b?source=rss-2fa221041436------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e4968990a7b</guid>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[dsa-training]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Athul A R]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 04:19:29 GMT</pubDate>
            <atom:updated>2024-08-12T17:23:58.294Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>These are mostly notes from the excellent book, <a href="https://dataintensive.net/">Designing Data Intensive Applications</a>.</blockquote><h3>ACID Transactions</h3><p>A database transaction is a logical unit that generally includes several low-level steps. ACID is a set of expectations that ensure any database transactions are processed in a reliable way, resulting in correctness.</p><ol><li>Atomicity here is better thought of as abortability. It means you can safely abort and retry any transaction.</li><li>Consistency means database remains in a good state. But, it is not really a property of transactions since applications can mess up invariants of the system with database not being able to do anything about it.</li><li>Isolation means concurrently executing transactions are isolated from each other.</li><li>Durability refers to resiliency to data corruption. Techniques involved are write ahead logs, replication, non-volatile storage etc. But, these are only risk-reduction techniques and not guarantees.</li></ol><p>The main concern of this discussion is Isolation. Why is this important? Most <em>ACID</em> databases are not serializable — transactions are not done as if they were executed one after the other — due to the high performance costs.</p><h3>Problems</h3><p>Partial implementations of ACID compliance could result in several application-level problems.</p><p>They are discussed below in the increasing order of difficulty.</p><h4>Dirty reads</h4><ul><li>Problem: seeing data that is not committed.</li><li>For avoiding dirty reads — read locks are possible but it has scalability issues.</li><li>Better solution: databases remember the old and new values. Until transaction is complete, it returns the old value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUGwnd3ZoeB2cxcvgdHHPw.png" /></figure><h4>Dirty writes</h4><ul><li>Problem: overwriting uncommitted data.</li><li>Solution — Write locks at row-level can stop this and abort the latter transaction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_IjcB74ZXDshMWakY0DQA.png" /></figure><h4>Read skew</h4><ul><li>Also called non-repeatable read.</li><li>Problem: a general version of dirty reads where phantom read results seemingly violate invariants.</li><li>Solution: We add version control to be able to see the state at different points in time; it is called MVCC (multi-version concurrency control). So, we can do consistent reads from a snapshot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OX0OxThLnqt39zHjH8p2A.png" /></figure><h4>Lost updates</h4><ul><li>Problem: concurrent writes on a single object result in second write killing the first.</li><li>For avoiding lost updates, the database can employ atomic write or compare set operations, explicit locking. But, both need care from developer side to be fully correct.</li><li>Automatically detecting lost updates is possible and efficient in conjunction with snapshot isolation. With this, the database can abort and force the second transaction to retry.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IKGXm8EB3bXSxsufaONDw.png" /></figure><h4>Write skew</h4><ul><li>It is a generalisation of the lost update problem.</li><li>Detection requires true serializability.</li><li>But, selective locking can help as a second-best solution. But, onus to get it right is on developer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmQefSe_vnAS5Crphmd9mg.png" /></figure><h3>Isolation Levels</h3><p>Databases advertise various levels of weak isolation levels while certifying themselves as ACID compliant.</p><p>The common levels are mentioned below.</p><h4>Read committed</h4><ol><li>No dirty reads.</li><li>No dirty writes.</li></ol><h4>Snapshot isolation</h4><ol><li>No dirty reads.</li><li>No dirty writes.</li><li>No read skew.</li></ol><h4>Atomic write support (non-standard)</h4><ol><li>No lost updates.</li></ol><h4>Conflict materialization (non-standard)</h4><p><strong>Context</strong>: Phantom is when a write in one transaction changing the result of a search query in another transaction.</p><p>Examples: Snapshot isolation avoids phantoms in read-only queries. Locking or serializabillity avoids phantoms in write queries.</p><p>One way to solve write skew is by materialising the phantom into a concrete entry. In the example above, it could be a timelock entry for Alice for that day before she can remove herself from Patrol. Due to its error-prone nature, serializable isolation is preferred over it.</p><ol><li>No dirty reads.</li><li>No dirty writes.</li><li>No write skew.</li></ol><h4>Serializable Isolation</h4><ol><li>No dirty reads.</li><li>No dirty writes.</li><li>No read skew.</li><li>No lost updates.</li><li>No write skew.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e4968990a7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>