{"action":"created","comment":{"url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/comments/93523866","pull_request_review_id":14053991,"id":93523866,"diff_hunk":"@@ -1,11 +1,628 @@\n ---\n layout: page\n-title:  \"Languages for Consistency\"\n-by: \"Joe Schmoe and Mary Jane\"\n+title:  \"Formal, Yet Relaxed: Models for Consistency\"\n+by: \"James Larisch\"\n ---\n+# Formal, Yet Relaxed: Models for Consistency\n \n-Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. {% cite Uniqueness --file langs-consistency %}\n+## What's the problem?\n+   In many ways, web developers deal with distributed systems problems every day: your client and your server are in two different geographical locations, and thus, some coordination between computers is required.\n+\n+  As Aviral discussed in the previous section, many computer scientists have done a lot of thinking about the nature of distributed systems problems. As such, we realize that it's impossible to completely emulate the behavior of a single computational machine using multiple machines. For example, the network is simply not as reliable as, say, memory - and waiting for responses can result in untimeliness for the application's userbase. After discussing the Consistency/Availability/Partition-tolerance theorem, Section 6 discussed how we can make drill down into the CAP pyramid and choose the necessary and unnecessary properties of our systems. As stated, we can't perfectly emulate a single computer using multiple machines, but once we accept that fact and learn to work with it, there are plenty of things we *can* do!\n+\n+## The Shopping Cart\n+  Let's bring all these theorem talk back to reality. Let's say you're working at a new e-commerce startup, and you'd like to revolutionize the electronic shopping cart. You'd like to give the customer the ability to do the following:\n+  1. Log in to the site and add a candle to the cart while traveling in Beijing.\n+  1. Take a HyperLoop (3 hours) from Beijing to Los Angeles.\n+  1. Log back in, remove the candle from the cart, and add a skateboard.\n+  1. Take another HyperLoop train from Los Angeles to Paris (5 hours).\n+  1. Log back into the site, add another skateboard, and checkout.\n+\n+Let's assume you have a server in every single country, and customers connect to the geographically closest server.\n+\n+How can we ensure that the client sees the same cart at every point in her trip?\n+\n+If you only had one user of your website, this wouldn't be too hard. You could manually, constantly modify and check on all of your servers and personally make sure the state of the customer's shopping cart is consistent across every single server. But what happens when you have millions of customers and thus millions of shopping carts? That would be impossible to keep track of personally. Luckily, you're a programmer - this can be automated! You simply need to make sure that all of your computers stay in-sync, so if the customer checks her cart in Beijing, then in Paris, she sees the same thing.\n+\n+But as Section 6 has already explained, this is not so trivial. Messages between your servers in Beijing and Paris could be dropped, corrupted, reordered, duplicated, or delayed. Servers can crash. Sharks can cut the network cables between countries. Since you have no guarantees about when you'll be able to synchronize state between two servers, it's possible that the customer could see two different cart-states depending on which country she's in (which server she asks).\n+\n+It's possible to implement \"consensus\" protocols such as Paxos and 3-Phase-Commit that provide coordination between your machines. When failure happens, such as a network shark-attack, the protocol detects a lack of consistency and becomes *unavailable* - at least until it is consistent once more. For applications in which inconsistent state is dangerous, this is appropriate. For a shopping cart, this seems like overkill. If our shopping cart system experienced a failure and became unavailable, users would not be able to add or remove things from the cart. They also couldn't check out. This means our startup would lose money! Perhaps it's not so important that our clients' shopping carts be completely synchronized across the entire world at all times. After all, how often are people going to be doing such wanderlust shopping?\n+\n+This is an important moment. By thinking about our specific problem, we've realized a compromise we're willing to make: our users always need to be able to add things, remove things, and checkout. In other words, our service needs to be as *available* as possible. Servers don't necessarily need to agree all the time. We'd like them to, but the system shouldn't shut down if they don't. We'll find a way to deal with it.\n+\n+Turns out there's a company out there called Amazon.com - and they've been having a similar problem. Amazon sells things on their website too, and users can add and remove things from their cart. Amazon has lots of servers spread out across the world. They also have quite a few customers. They need to ensure their customers' carts are robust: if/when servers fail or lose communication with one another, a \"best-effort\" should be made to display the customer's cart. Amazon acknowledges that failure, latency, or HyperLoop-traveling users can cause inconsistent cart data, depending on which server you ask. How does Amazon resolve these issues?\n+\n+## Dynamo\n+Amazon built DynamoDB {% cite Dynamo --file langs-consistency %}, which is basically a big distributed hash table. In other words, it's a hashmap spread across multiple computers. A user's cart would be stored as a value under the user's username as the key. (`{'james': {'candle', 'skateboard'}}`) When a user adds a new item to her cart, the cart data is replicated across a multiple machines within the network. If the client changes locations then performs another write, or if a few machines fail and later recover, it's possible for different machines to have different opinions about the state of a given user's cart.\n+\n+Dynamo has a rather unique way of dealing with these types of conflicts. Since Dynamo always wants to be available for both writes and reads (add/removes, viewing/checkouts, resp) it must have a way of combining inconsistent data. Dynamo chooses to perform this resolution at read time. When a client performs a `get()` on the user's cart, Dynamo will take the multiple conflicting carts and push them up to the application! Huh? I thought Dynamo resolves this for the programmer!? Actually, Dynamo is a generic key-value store. It detects inconsistencies in the data - but once it does, it simply tells the application (in this case the application is the shopping cart code) that there are some conflicts. The application (shopping cart, in this case) is free to resolve these inconsistencies as it pleases.\n+\n+How should Amazon's shopping cart procede with resolution? It may be fed two cart states like so:\n+\n+```\n+James's Cart V1  |  James's Cart V2\n+-----------------------------------\n+Red Candle       |  Red Candle\n+Blue Skateboard  |  Green Umbrella\n+```\n+\n+Amazon doesn't want to accidently *remove* anything from your cart, so it errs on the side of inclusion. If given this particular conflict, you would see:\n+\n+```\n+James's Cart\n+------------\n+Red Candle\n+Blue Skateboard\n+Green Umbrella\n+```\n+\n+It's important to understand that Amazon has multiple machines storing the contents of your cart. These machines are asynchronously communicating in order to tell each other about updates they've received. Conflicts like this can happen when you try to read before the nodes have had time to gossip about your cart. More likely, however, is the situation in which one of the machines holding your cart goes offline and missing some updates. When it comes back online, you try to read, and this resolution process must occur.\n+\n+### Good & Bad\n+What do we love about Dynamo? It's a highly available key-value store. It replicates data well, and according to the paper, has high uptime and low latency. We love that it's *eventually consistent*. Nodes are constantly gossiping, so given enough time (and assuming failures are resolved), nodes' states will eventually converge. However, this property is *weak*. It's weak because when failures & conflicts occur, and [and they will occur](https://www.youtube.com/watch?v=JG2ESDGwHHY), it's up to the application developer to figure out how to handle it. Given a conflict, there isn't a one-size-fits-all solution for resolving them. In the case of the shopping cart, it's relatively trivial. But as a programmer, every time you use DynamoDB for a different purpose you need to consider your resolution strategy. The database doesn't provide a general solution.\n+\n+Instead of constructing an all-purpose database and forcing the burden of resolution on programmers, what if we constructed multi-purpose (read: multi, not *all*) data structures that required no manual resolution? These data structures would resolve conflicts inherently, themselves, and depending on your application you could choose which data structure works best for you.\n+\n+Let's try this transfiguration on the shopping cart. Let's strip it down: how does Amazon handle resolution, really? It treats shopping cart versions as sets of items. In order to perform resolution, Amazon unions the two sets.\n+\n+```\n+{ Red Candle, Blue Skateboard } U { Red Candle, Green Umbrella } == { Red Candle, Blue Skateboard, Green Umbrella }\n+```\n+\n+Using this knowledge, let's try to construct our own shopping cart that automatically resolves conflicts.\n+\n+(Unfortunately Amazon has a leg up on our startup. Their programmers have figured out a way to add multiple instances of a single item into the cart. Users on our website can only add one \"Red Candle\"\" to their shopping cart. This is due to a fundamental limitation in the type of CRDT I chose to exemplify. It's quite possible to have a fully functional cart. Take a look at LWW-Sets.)\n+\n+### Example\n+\n+Let's take a look at the following Javascript. For simplicity's sake, let's pretend users can only add things to their shopping cart.\n+\n+```javascript\n+class Cart {\n+  constructor(peers, socket) {\n+    this.mySocket = socket;\n+    this.peers = peers;\n+    this.items = new Set();\n+  }\n+\n+  addItem(item) {\n+    this.items.add(item);\n+  }\n+\n+  synchronize() {\n+    peers.forEach(function(peer) {\n+      peer.send(items);\n+    });\n+  }\n+\n+  receiveState(items) {\n+    this.items = this.items.union(items);\n+  }\n+\n+  run() {\n+    var clientAddition = Interface.nonBlockingReceiveInput(); // invented\n+    if (clientAddition !== undefined) {\n+      this.addItem(clientAddition);\n+    }\n+    var receivedState = mySocket.nonBlockingRead(); // invented\n+    if (receivedState !== undefined) {\n+      this.receiveState(receivedState);\n+    }\n+    synchronize();\n+    sleep(10);\n+    run();\n+  }\n+}\n+\n+// theoretical usage\n+\n+var socket = new UDPSocket(); // invented\n+var cart = new Cart(peerSockets, socket); // peerSockets is an array of UDP sockets\n+cart.run();\n+cart.items // the cart's items\n+```\n+\n+Here is an (almost) fully functional shopping cart program. You can imagine this code running across multiple nodes scattered over the world. The meat of the program lies in the `run()` method. Let's walk through that:\n+  1. Program receives an addition to the cart from the user.\n+  2. Program adds that item to the current local state if it exists.\n+  3. Program checks its UDP socket for any messages.\n+  4. If it received one, it's means another instance of this program has sent us its state. What is state in this case? Simply a set of cart items. Let's handle this set of items by unioning it with our current set.\n+  5. Synchronize our current state by sending our state to every peer that we know about.\n+  6. Sleep for 10 seconds.\n+  7. Repeat!\n+\n+Hopefully it's clear that if a client adds an item to her cart in Beijing and then 10 seconds later checks her cart in Paris, she should see the same thing. Well, not exactly - remember, the network is unreliable, and Beijing's `synchronize` messages might have been dropped. But no worries! Beijing is `synchronizing` again in another 10 seconds. This should remind you of Dynamo's gossiping: nodes are constantly attempting to converge.\n+\n+Both systems are eventually consistent - the difference here is our Javascript shopping cart displays *strong* eventual consistency. It's strong because it requires no specialized resolution. When a node transmits its state to another node, there's absolutely no question about how to integrate that state into the current one. There's no conflict.\n+\n+### The Intern\n+Unfortunately Jerry, the intern, has found your code. He'd like to add `remove` functionality to the cart. So he makes the following changes:\n+\n+```javascript\n+class Cart {\n+  constructor(peers, socket) {\n+    this.mySocket = socket;\n+    this.peers = peers;\n+    this.items = new Set();\n+  }\n+\n+  addItem(item) {\n+    this.items.add(item);\n+  }\n+\n+  synchronize() {\n+    peers.forEach(function(peer) {\n+      peer.send(items);\n+    });\n+  }\n+\n+  receiveState(items) {\n+    // JERRY WAS HERE\n+    this.items = this.items.intersection(items);\n+    // END JERRY WAS HERE\n+  }\n+\n+  run() {\n+    var clientAddition = Interface.nonBlockingReceiveInput(); // invented\n+    if (clientAddition !== undefined) {\n+      this.addItem(clientAddition);\n+    }\n+    // JERRY WAS HERE\n+    var clientDeletion = Interface.nonBlockingReceiveInput():\n+    if (clientDeletion !== undefined) {\n+      this.items.delete(clientDeletion);\n+    }\n+    // END JERRY WAS HERE\n+    var receivedState = mySocket.nonBlockingRead(); // invented\n+    if (receivedState !== undefined) {\n+      this.receiveState(receivedState);\n+    }\n+    synchronize();\n+    sleep(10);\n+    run();\n+  }\n+}\n+\n+// theoretical usage\n+\n+var socket = new UDPSocket(); // invented\n+var cart = new Cart(peerSockets, socket); // peerSockets is an array of UDP sockets\n+cart.run();\n+cart.items // the cart's items\n+```\n+\n+Uh-oh. Can you spot the problem? Let's break it down. In the original code, the current node's cart items were *unioned* with the communicating node's cart. Since there was no deletion, carts could only ever expand. Here was Jerry's plan:\n+\n+```\n+> I want to delete things. If you delete something from node 1, and intersect it's state from node 2, the item will be deleted from node 2 as well.\n+\n+Node 1: { A, B }\n+Node 2: { A, B }\n+\n+delete(Node2, A)\n+\n+Node 1: { A, B }\n+Node 2: { B }\n+\n+Node1 = Node1.intersect(Node2)\n+Node1: { B }\n+```\n+\n+The reasoning is sound. However, there's a huge issue here. We've flipped the `union` operation on its head! Now, carts can *never* expand! They can only either stay the same size or shrink. So although Jerry's contrived example works, it's impossible to ever reach the beginning states of Node 1 and Node 2 unless those two nodes receive *the same writes*. Let's take it from the top:\n+\n+```\n+Node 1: { }\n+Node 2: { }\n+\n+add(Node1, A)\n+add(Node2, B)\n+\n+Node 1: { A }\n+Node 2: { B }\n+\n+Node1_temp = Node1.intersect(Node2)\n+Node2_temp = Node2.intersect(Node1)\n+Node1 = Node1_temp\n+Node2 = Node2_temp\n+\n+Node 1: { }\n+Node 2: { }\n+```\n+\n+This is pretty nasty. Jerry has come along and with a few lines of code he's obliterated our nice strong eventually consistent code. Surely there's a better way.\n+\n+### Guarantees\n+The original Javascript we wrote down exhibits the property from Section 6 known as logical *monotonicity*. The union operation ensures that a given node's state is always \"greater than or equal to\" the states of the other nodes. However, how can we be *sure* that this property is maintained throughout the development of this program? As we've seen, there's nothing stopping an intern from coming along, making a mindless change, and destroying this wonderful property. Ideally, we want to make it impossible (or at least very difficult) to write programs that violate this property. Or, at the very least, we want to make it very easy to write programs that maintain these types of properties.\n+\n+But where should these guarantees live? In the above Javascript example, the guarantees aren't guarantees at all, really. There's no restriction on what the programmer is allowed to do - the programmer has simply constructed a program that mirrors guarantees that she has modeled in her brain. In order to maintain properties such as *monotonicity*, she must constantly check the model in her brain against the code. We haven't really helped the programmer out that much - she has a lot of thinking to do.\n+\n+Databases such as PostgreSQL have issues like this as well, though they handle them quite differently, masters may need to ensure that writes have occurred on every slave before the database becomes available for reading. A database system like this has pushed consistency concerns to the IO-level, completely out of the users control. They are enforced on system reads and system writes. This approach gives programmers no flexibility: as demonstrated with our shopping cart example, there's no need for these type of restrictions; we can tolerate inconsistency in order to maintain availability.\n+\n+Why not push the consistency guarantees in between the IO-level and the application-level? {% cite ConsistencyWithoutBorders --file langs-consistency %} Is there any reason why you as the programmer couldn't program using tools that facilitate these types of monotonic programs? If you're familiar with formal systems -- why not construct a formal system (programming language / library) in which every theorem (program) is formally guaranteed to be monotonic? If it's *impossible* to express a non-monotonic program, the programmer needn't worry about maintaining a direct mapping between their code and his or her mental model.\n+\n+Wouldn't it be great if tools like this existed?\n+\n+### Bloom\n+Before talking about such tools, I'd like you to forget almost everything you know about programming for a second (unless of course you've never programmed in a Von Neumann-based language in which you sequentially update pieces of memory; which, by the way, you have).\n+\n+Imagine the following scenario: you are \"programming\" a node in a cluster of computers. All of the other computers work as expected. When you receive a message (all messages will include an integer), your task is to save the message, increment the integer, and resend the message back to its originator. You must also send messages you've received from `stdin`. Unfortunately, the programming environment is a little strange.\n+You have access to five buffers:\n+* Messages you have received in the last 5 seconds\n+* Inputs you've received from `stdin` in the last 5 seconds\n+* An outgoing messages buffer: flushed & sent every 5 seconds\n+* A bucket of saved messages: *never* flushed\n+\n+However, you only have access to these buffers *every 5 seconds*. If messages are formatted as such: `(SOURCE, INTEGER, T)`, your buffers might look like when `t = 0`. (`t` is the number of seconds elapsed)\n+\n+```\n+<T = 0>\n+RECV-BUFFER: [(A, 1, 0), (B, 2, 0)]\n+RSTDIN-INPUTS: [(A, 5, 0), (C, 10, 0)]\n+SEND-BUFFER: []\n+SAVED: [(D, -1, 0), (E, -100, 0)]\n+```\n+\n+If you don't write any code to manipulate these buffers, when `t = 5`, your buffers might look like:\n+\n+```\n+<T = 5>\n+RECV-BUFFER: [(C, 10, 5)]\n+STDIN-INPUTS: [(X, 1, 5)]\n+SEND-BUFFER: []\n+SAVED: [(D, -1, 0), (E, -100, 0)]\n+```\n+\n+You can see that from `t = 0` to `t = 5`, you received one message from `C` and someone typed a message to `X` via `stdin`.\n+\n+Remember our goals?\n+* Save received messages from the network\n+* Send out messages received from `stdin`\n+* For all received network messages, increment the integer and resend it back to the originator\n+\n+In Javascript, perhaps you code up something like this:\n+\n+```javascript\n+onFiveSecondInterval(function() {\n+  recvBuffer.forEach(function(msg) {\n+    savedBuffer.push(msg);            // save message\n+    let newMsg = msg.clone()\n+    newMsg.integer++;                 // increment recv'd message\n+    newMsg.flipSourceDestination()\n+    sendBuffer.push(newMsg);          // send it out\n+  });\n+\n+  stdinInputBuffer.forEach(function(msg) {\n+    sendBuffer.push(msg);             // send stdin message\n+  });\n+});\n+```\n+\n+or Ruby:\n+\n+```ruby\n+on_five_second_interval do\n+  recv_buffer.each do |msg|\n+    saved_buffer << msg\n+    new_msg = msg.clone\n+    new_msg.integer += 1\n+    new_msg.flip_source_destination\n+    send_buffer << new_msg\n+  end\n+\n+  stdin_input_buffer.each do |msg|\n+    send_buffer << msg\n+  end\n+end\n+```\n+\n+We have expressed this model using an event-driven programming style: the callbacks are triggered when `t % 5 = 0`: when the buffers populate & flush.\n+\n+Notice we perform a few \"copies\". We read something from one buffer and place it into another one, perhaps after applying some modification. Perhaps we place a message from a given buffer into two buffers (`recv_buffer` to `saved_buffer` & `send_buffer`).\n+\n+This situation screams for a more functional approach:\n+```ruby\n+on_five_second_interval do\n+  saved_buffer += recv_buffer             # add everything in recv_buffer to saved_buffer\n+\n+  send_buffer += recv_buffer.map do |msg| # map over the recv_buffer, increment integers, add to send_buffer\n+    new_msg = msg.clone\n+    new_msg.integer += 1\n+    new_msg.flip_source_destination       # send to originator\n+    new_msg                               # this block returns new_msg\n+  end\n+\n+  send_buffer += stdin_input_buffer       # add stdin messages to the send buffer\n+end\n+```\n+\n+After this block/callback is called, the system automatically flushes & routes messages as described above.\n+\n+Bloom {% cite Bloom --file langs-consistency %}, a research language developed at UC Berkeley, has a similar programming model to the one described above. Execution is broken up into a series of \"timesteps\". In the above example, one \"timestemp\" would be the execution of one `on_five_second_interval` function. Bloom, like the theoretical system above, automatically flushes and populates certain buffers before and after each timestep. In the above example, 5 seconds was an arbitrary amount of time. In Bloom, timesteps (rounds of evaluation) are logical tools - they may happen every second, 10 seconds, etc. Logically, it shouldn't affect how your program executes. In reality, Bud's timesteps correspond to evaluation iterations. Your code is evaluated, executed, and the process repeats.\n+\n+So what does a Bloom program look like? Bloom's prototypal implementation is called Bud and is implemented in Ruby. There are two main parts to a Bloom program:\n+1. User defined buffers: rather than the four buffers I gave you above, Bloom users can define their own buffers. There are different types of buffers depending on the behavior you desire:\n+  * `channel`: Above, `recv_buffer` and `send_buffer` would be considered channels. They facilitate sending network messages to and from other nodes. Like the messages above, messages sent into these channels contain a \"location-specifier\", which tells Bloom where the message should be sent. If you wanted to send a message to `A`, you could push the message `(@A, 10)` into your send buffer (in Ruby, `[\"@A\", 10]`). The `@` denotes the location-specifier. At the end of the timestep (or callback execution in the above example), these buffers are flushed.\n+  * `table`: Above, `saved_buffer` would be considered a table. The contents of tables persist across timesteps, which means tables are never flushed.\n+2. Code to be executed at each timestep. A Bloom (Bud) program can be seen as the inside of the block passed to `on_five_second_interval`. In fact, it looks very similar, as we'll see.\n+\n+For the purposes of this chapter, let's assume `stdin_input_buffer` is a special kind of channel in which are sent in via `stdin`. Let's also assume this channel exists in all Bloom programs.\n+\n+Let's take a look at an example Bud program.\n+\n+First, let's declare our state.\n+\n+```ruby\n+module Incrementer\n+  def state\n+    channel :network_channel ['@dst', 'src', 'integer']\n+    table :saved_buffer ['dst', 'src', 'integer']\n+    # implied channel :stdin_input_buffer ['@dst', 'src', 'integer']\n+  end\n+end\n+```\n+\n+The first line of `state` means: declare a channel called `network_channel` in which messages are 3-tuples. The first field of the message is called `dst`, the second `src`, and the third is called `integer`. `@` is our location-specifier, so if a program wants to send a message to a node at a given identifier, they will place it in the first `dst` field. For example, a message destined for `A` would look like `['A', 'me', 10]`. The `@` denotes the location-specifier within the collection's \"schema\".\n+\n+The second line means: declare a table (persists) called `saved_buffer` in which messages follow the same format as `network_channel`. There's no location specifier since this collection is not network-connected.\n+\n+You can think of the Ruby array after the channel name as the \"schema\" of that collection.\n+\n+Notice how we only have one network channel for both receiving and sending. Before, we had two buffers, one for sending and one for receiving. When we place items *into* `network_channel`, Bud will automatically send messages to the appropriate `@dst`.\n+\n+Next, let's write our code. This code will be executed at every timestamp. In fact, you can think of a Bud program as the code inside of a timestamp callback. Let's model the raw Ruby code we saw above.\n+\n+```ruby\n+module Incrementer\n+  def state\n+    channel :network_channel ['@dst', 'src', 'integer']\n+    table :saved_buffer ['dst', 'src', 'integer']\n+    # implied channel :stdin_input_buffer ['@dst', 'src', 'integer']\n+  end\n+\n+  declare\n+  def increment_messages\n+    network_channel <~ network_channel.map { |x| [x.src, x.dst, x.integer + 1] }\n+  end\n+\n+  declare\n+  def save_messages\n+    saved_buffer <= network_channel\n+  end\n+\n+  declare\n+  def send_messages\n+    network_channel <~ stdin_input_buffer\n+  end\n+end\n+```\n+\n+Don't panic. Remember - the output of this program is identical to our Ruby callback program from earlier. Let's walk through it step by step.\n+```ruby\n+declare\n+def increment_messages\n+  network_channel <~ network_channel.map { |x| [x.src, x.dst, x.integer] }\n+end\n+```\n+Here, we take messages we've received from the network channel and send them back into the network channel. The `<~` operator says \"copy all of the elements in the right-hand-side and eventually send them off onto the network in the channel on the left-hand-side\". So, we map over the contents of network channel *in the current timestep*: switching the `src` and `dst` fields, and incrementing the integer. This mapped collection is passed back into the network channel. Bud will ensure that those messages are sent off at some point.\n+\n+```\n+declare\n+def save_messages\n+  saved_buffer <= network_channel\n+end\n+```\n+In `save_messages`, we use the `<=` operator. `<=` says \"copy all of the elements in the right-hand-side and add them to the table on the left-hand-side.\" It's important to note that this movement occurs *within the current timestep*. This means if `saved_buffer` is referenced elsewhere in the code, it will include the contents of `network_channel`. If we had used the `<+` operator instead, the contents of `network_channel` would show up in `saved_buffer` in the *next* timestep. The latter is useful if you'd like to operate on the current contents of `saved_buffer` in the current timestep but want to specify how `saved_buffer` should be updated for the next timestep.\n+\n+Remember, all of this code is executed in *each* timestep - the separation of code into separate methods is merely for readability.\n+\n+```\n+declare\n+def send_messages\n+  network_channel <~ stdin_input_buffer\n+end\n+```\n+\n+`send_messages` operates very much like `increment_messages`, except it reads the contents of `stdin_input_buffer` and places them into the network channel to be sent off at an indeterminite time.\n+\n+#### Details\n+\n+Examine Bloom's \"style\". Compare it to your standard way of programming. Compare it to the Javascript & Ruby timestep/callback examples. Bloom has a more \"declarative\" style: what does this mean? Look at our Javascript:\n+\n+```javascript\n+onFiveSecondInterval(function() {\n+  recvBuffer.forEach(function(msg) {\n+    savedBuffer.push(msg);            // save message\n+    let newMsg = msg.clone()\n+    newMsg.integer++;                 // increment recv'd message\n+    newMsg.flipSourceDestination();\n+    sendBuffer.push(newMsg);          // send it out\n+  });\n+\n+  stdinInputBuffer.forEach(function(msg) {\n+    sendBuffer.push(msg);             // send stdin message\n+  });\n+});\n+```\n+\n+\"Every five seconds, loop over the received messages. For each message, do this, then that, then that.\" We are telling the computer each step we'd like it to perform. In Bud, however, we describe the state of tables and channels at either the current or next timestep using operators and other tables and channels. We describe what we'd like our collections to include and look like, rather than what to do. You declare what you'd like the state of the world to be at the current instant and at following instants.\n+\n+#### Isn't this chapter about consistency?\n+\n+It's time to implement our shopping cart in Bloom. We are going to introduce one more collection: a `periodic`. For example, `periodic :timer 10` instantiates a new periodic collection. This collection becomes \"populated\" every 10 seconds. Alone, it's not all that useful. However, when `join`'d with another table, it can be used to perform actions every `x` seconds.\n+\n+```ruby\n+module ShoppingCart\n+  include MulticastProtocol\n+\n+  def state\n+    table :cart ['item']\n+    channel :recv_channel ['@src', 'dst', 'item']\n+    # implied channel :stdin_input_buffer ['item']\n+    periodic :timer 10\n+  end\n+\n+  declare\n+  def add_items\n+    cart <= stdin_input_buffer\n+  end\n+\n+  declare\n+  def send_items\n+    send_mcast <= join([cart, timer]).map { |item, timer| item }\n+  end\n+\n+  declare\n+  def receive_items\n+    cart <+ recv_channel.map { |x| x.item }\n+  end\n+end\n+```\n+\n+`send_mcast` is a special type of channel we receive from the `MulticastProtocol` mixin. It sends all items in the right-hand-side to every known peer.\n+* `add_items`: receive items from stdin, add them to the cart\n+* `send_items`: join our cart with the 10-second timer. Since the timer only \"appears\" every 10 seconds, this `join` will produce a result every 10 seconds. When it does, send all cart items to all peers via `send_mcast`.\n+* `receive_items`: when we receive a message from a peer, add the item to our cart.\n+\n+Functionally, this code is equivalent to our working Javascript shopping cart implementation. However, there are a few important things to note:\n+* In our Javascript example, we broadcasted our entire cart to all peers. When a peer received a message, they unioned their current cart with the received one. Here, each node broadcasts each element in the cart. When a node receives an item, it adds it to the current cart. Since tables are represented as sets, repeated or unordered additions do not matter. You can think of `{A, B, C}.add(D)` as equivalent to `{A, B, C}.union({D})`.\n+* You cannot add items twice. Since tables are represented as sets and we simply add items to our set, an item can only ever exist once. This was true of our Javascript example as well.\n+* You still cannot remove items!\n+\n+Bloom has leveraged the montononic, add-only set and constructed a declarative programming model based around these sets. When you treat everything as sets (not unlike SQL) and you introduce the notion of \"timestemps\", you can express programs as descriptions of state rather than an order of operations. Besides being a rather unique model, Bloom presents an accessible and (perhaps...) safe model for programming eventually consistent programs.\n+\n+#### Sets only?\n+Bloom's programming model is built around the set. As Aviral discussed in the previous chapter, however, sets are not the only monotonic data structures. Other CRDTs are incredibly useful for programming eventually consistent distributed programs.\n+\n+Recall that a *bounded join semilattice* (CRDT) can be represented as a 3-tuple: `(S, U, ⊥)`. `S` is the set of all elements within the semilattice. `U` is the `least-upper bound` operation. `⊥` is the \"least\" element within the set. For example, for add-only sets, `S = the set of all sets`, `U = union` and `⊥ = {}`. Elements of these semilattices, when `U` is applied, can only \"stay the same or get larger\". Sets can only stay the same size or get larger - they can never rollback. For some element `e` in `S`, `e U ⊥` must equal `e`.\n+For a semilattice we'll call `integerMax`, `S = the set of all integers`, `U = max(x, y)`, and `⊥ = -Infinity`. Hopefully you can see that elements of this lattice (integers) \"merged\" with other elements of this lattice never produce a result less than either of the merged elements.\n+\n+These semilattices (and many more!) can be used to program other types of distributed, eventually consistent programs. Although sets are powerful, there might be more expressive ways to describe your program. It's not difficult to imagine using `integerMax` to keep a global counter across multiple machines.\n+\n+Unfortunately, Bloom does not provide support for other CRDTs. In fact, you cannot define your own datatypes at all. You are bound by the collections described.\n+\n+Bloom<sup>L</sup>{% cite BloomL --file langs-consistency %}, an addendum to the Bloom language, provides support for these types of data structures. Specifically, Bloom<sup>L</sup> does two things:","path":"chapter/7/langs-consistency.md","position":506,"original_position":506,"commit_id":"84a9fbf592cc376a41600d0d0fdc7bf18fb4dd30","original_commit_id":"84a9fbf592cc376a41600d0d0fdc7bf18fb4dd30","user":{"login":"semaj","id":5074906,"avatar_url":"https://avatars.githubusercontent.com/u/5074906?v=3","gravatar_id":"","url":"https://api.github.com/users/semaj","html_url":"https://github.com/semaj","followers_url":"https://api.github.com/users/semaj/followers","following_url":"https://api.github.com/users/semaj/following{/other_user}","gists_url":"https://api.github.com/users/semaj/gists{/gist_id}","starred_url":"https://api.github.com/users/semaj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/semaj/subscriptions","organizations_url":"https://api.github.com/users/semaj/orgs","repos_url":"https://api.github.com/users/semaj/repos","events_url":"https://api.github.com/users/semaj/events{/privacy}","received_events_url":"https://api.github.com/users/semaj/received_events","type":"User","site_admin":false},"body":"I'm torn on this. These and the Bloom analysis tool are integral parts of the Bloom works, but I have doubts about a general audience's ability to understand them. \r\n\r\nPerhaps I'm not considering the correct audience - my intent with this chapter was to provide a foundation for understanding these new consistency mechanisms and tools. It seemed like discussing morphisms and monotone functions was a quick way to discourage / scare off your average programmer. The same goes for the analysis tool. I'm not sure the average web developer necessarily cares about how the Bloom monotonic-dependency graph is constructed. \r\n\r\nShould this chapter aim to be a comprehensive study on the subject or a digestible yet thorough introduction to these ideas? \r\n\r\n@heathermiller what are your thoughts on this?","created_at":"2016-12-21T21:34:51Z","updated_at":"2016-12-21T21:34:51Z","html_url":"https://github.com/heathermiller/dist-prog-book/pull/2#discussion_r93523866","pull_request_url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2","_links":{"self":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/comments/93523866"},"html":{"href":"https://github.com/heathermiller/dist-prog-book/pull/2#discussion_r93523866"},"pull_request":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2"}}},"pull_request":{"url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2","id":94265019,"html_url":"https://github.com/heathermiller/dist-prog-book/pull/2","diff_url":"https://github.com/heathermiller/dist-prog-book/pull/2.diff","patch_url":"https://github.com/heathermiller/dist-prog-book/pull/2.patch","issue_url":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/2","number":2,"state":"closed","locked":false,"title":"FIRST DRAFT","user":{"login":"semaj","id":5074906,"avatar_url":"https://avatars.githubusercontent.com/u/5074906?v=3","gravatar_id":"","url":"https://api.github.com/users/semaj","html_url":"https://github.com/semaj","followers_url":"https://api.github.com/users/semaj/followers","following_url":"https://api.github.com/users/semaj/following{/other_user}","gists_url":"https://api.github.com/users/semaj/gists{/gist_id}","starred_url":"https://api.github.com/users/semaj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/semaj/subscriptions","organizations_url":"https://api.github.com/users/semaj/orgs","repos_url":"https://api.github.com/users/semaj/repos","events_url":"https://api.github.com/users/semaj/events{/privacy}","received_events_url":"https://api.github.com/users/semaj/received_events","type":"User","site_admin":false},"body":"","created_at":"2016-11-17T22:30:51Z","updated_at":"2016-12-21T21:34:51Z","closed_at":"2016-12-18T20:53:57Z","merged_at":"2016-12-18T20:53:57Z","merge_commit_sha":"5b299d189255e04ca3481a15e15b2a2e10b29b42","assignee":null,"assignees":[],"milestone":null,"commits_url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2/commits","review_comments_url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2/comments","review_comment_url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/comments{/number}","comments_url":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/2/comments","statuses_url":"https://api.github.com/repos/heathermiller/dist-prog-book/statuses/84a9fbf592cc376a41600d0d0fdc7bf18fb4dd30","head":{"label":"semaj:larisch-first-draft","ref":"larisch-first-draft","sha":"84a9fbf592cc376a41600d0d0fdc7bf18fb4dd30","user":{"login":"semaj","id":5074906,"avatar_url":"https://avatars.githubusercontent.com/u/5074906?v=3","gravatar_id":"","url":"https://api.github.com/users/semaj","html_url":"https://github.com/semaj","followers_url":"https://api.github.com/users/semaj/followers","following_url":"https://api.github.com/users/semaj/following{/other_user}","gists_url":"https://api.github.com/users/semaj/gists{/gist_id}","starred_url":"https://api.github.com/users/semaj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/semaj/subscriptions","organizations_url":"https://api.github.com/users/semaj/orgs","repos_url":"https://api.github.com/users/semaj/repos","events_url":"https://api.github.com/users/semaj/events{/privacy}","received_events_url":"https://api.github.com/users/semaj/received_events","type":"User","site_admin":false},"repo":{"id":74066430,"name":"dist-prog-book","full_name":"semaj/dist-prog-book","owner":{"login":"semaj","id":5074906,"avatar_url":"https://avatars.githubusercontent.com/u/5074906?v=3","gravatar_id":"","url":"https://api.github.com/users/semaj","html_url":"https://github.com/semaj","followers_url":"https://api.github.com/users/semaj/followers","following_url":"https://api.github.com/users/semaj/following{/other_user}","gists_url":"https://api.github.com/users/semaj/gists{/gist_id}","starred_url":"https://api.github.com/users/semaj/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/semaj/subscriptions","organizations_url":"https://api.github.com/users/semaj/orgs","repos_url":"https://api.github.com/users/semaj/repos","events_url":"https://api.github.com/users/semaj/events{/privacy}","received_events_url":"https://api.github.com/users/semaj/received_events","type":"User","site_admin":false},"private":false,"html_url":"https://github.com/semaj/dist-prog-book","description":null,"fork":true,"url":"https://api.github.com/repos/semaj/dist-prog-book","forks_url":"https://api.github.com/repos/semaj/dist-prog-book/forks","keys_url":"https://api.github.com/repos/semaj/dist-prog-book/keys{/key_id}","collaborators_url":"https://api.github.com/repos/semaj/dist-prog-book/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/semaj/dist-prog-book/teams","hooks_url":"https://api.github.com/repos/semaj/dist-prog-book/hooks","issue_events_url":"https://api.github.com/repos/semaj/dist-prog-book/issues/events{/number}","events_url":"https://api.github.com/repos/semaj/dist-prog-book/events","assignees_url":"https://api.github.com/repos/semaj/dist-prog-book/assignees{/user}","branches_url":"https://api.github.com/repos/semaj/dist-prog-book/branches{/branch}","tags_url":"https://api.github.com/repos/semaj/dist-prog-book/tags","blobs_url":"https://api.github.com/repos/semaj/dist-prog-book/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/semaj/dist-prog-book/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/semaj/dist-prog-book/git/refs{/sha}","trees_url":"https://api.github.com/repos/semaj/dist-prog-book/git/trees{/sha}","statuses_url":"https://api.github.com/repos/semaj/dist-prog-book/statuses/{sha}","languages_url":"https://api.github.com/repos/semaj/dist-prog-book/languages","stargazers_url":"https://api.github.com/repos/semaj/dist-prog-book/stargazers","contributors_url":"https://api.github.com/repos/semaj/dist-prog-book/contributors","subscribers_url":"https://api.github.com/repos/semaj/dist-prog-book/subscribers","subscription_url":"https://api.github.com/repos/semaj/dist-prog-book/subscription","commits_url":"https://api.github.com/repos/semaj/dist-prog-book/commits{/sha}","git_commits_url":"https://api.github.com/repos/semaj/dist-prog-book/git/commits{/sha}","comments_url":"https://api.github.com/repos/semaj/dist-prog-book/comments{/number}","issue_comment_url":"https://api.github.com/repos/semaj/dist-prog-book/issues/comments{/number}","contents_url":"https://api.github.com/repos/semaj/dist-prog-book/contents/{+path}","compare_url":"https://api.github.com/repos/semaj/dist-prog-book/compare/{base}...{head}","merges_url":"https://api.github.com/repos/semaj/dist-prog-book/merges","archive_url":"https://api.github.com/repos/semaj/dist-prog-book/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/semaj/dist-prog-book/downloads","issues_url":"https://api.github.com/repos/semaj/dist-prog-book/issues{/number}","pulls_url":"https://api.github.com/repos/semaj/dist-prog-book/pulls{/number}","milestones_url":"https://api.github.com/repos/semaj/dist-prog-book/milestones{/number}","notifications_url":"https://api.github.com/repos/semaj/dist-prog-book/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/semaj/dist-prog-book/labels{/name}","releases_url":"https://api.github.com/repos/semaj/dist-prog-book/releases{/id}","deployments_url":"https://api.github.com/repos/semaj/dist-prog-book/deployments","created_at":"2016-11-17T20:52:01Z","updated_at":"2016-11-17T20:52:02Z","pushed_at":"2016-12-21T21:29:11Z","git_url":"git://github.com/semaj/dist-prog-book.git","ssh_url":"git@github.com:semaj/dist-prog-book.git","clone_url":"https://github.com/semaj/dist-prog-book.git","svn_url":"https://github.com/semaj/dist-prog-book","homepage":null,"size":9085,"stargazers_count":0,"watchers_count":0,"language":"HTML","has_issues":false,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":0,"mirror_url":null,"open_issues_count":0,"forks":0,"open_issues":0,"watchers":0,"default_branch":"master"}},"base":{"label":"heathermiller:master","ref":"master","sha":"d4e0f859d700cd6a3c8a2d1b41821d0fa5da70cb","user":{"login":"heathermiller","id":687163,"avatar_url":"https://avatars.githubusercontent.com/u/687163?v=3","gravatar_id":"","url":"https://api.github.com/users/heathermiller","html_url":"https://github.com/heathermiller","followers_url":"https://api.github.com/users/heathermiller/followers","following_url":"https://api.github.com/users/heathermiller/following{/other_user}","gists_url":"https://api.github.com/users/heathermiller/gists{/gist_id}","starred_url":"https://api.github.com/users/heathermiller/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/heathermiller/subscriptions","organizations_url":"https://api.github.com/users/heathermiller/orgs","repos_url":"https://api.github.com/users/heathermiller/repos","events_url":"https://api.github.com/users/heathermiller/events{/privacy}","received_events_url":"https://api.github.com/users/heathermiller/received_events","type":"User","site_admin":false},"repo":{"id":71059722,"name":"dist-prog-book","full_name":"heathermiller/dist-prog-book","owner":{"login":"heathermiller","id":687163,"avatar_url":"https://avatars.githubusercontent.com/u/687163?v=3","gravatar_id":"","url":"https://api.github.com/users/heathermiller","html_url":"https://github.com/heathermiller","followers_url":"https://api.github.com/users/heathermiller/followers","following_url":"https://api.github.com/users/heathermiller/following{/other_user}","gists_url":"https://api.github.com/users/heathermiller/gists{/gist_id}","starred_url":"https://api.github.com/users/heathermiller/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/heathermiller/subscriptions","organizations_url":"https://api.github.com/users/heathermiller/orgs","repos_url":"https://api.github.com/users/heathermiller/repos","events_url":"https://api.github.com/users/heathermiller/events{/privacy}","received_events_url":"https://api.github.com/users/heathermiller/received_events","type":"User","site_admin":false},"private":false,"html_url":"https://github.com/heathermiller/dist-prog-book","description":null,"fork":false,"url":"https://api.github.com/repos/heathermiller/dist-prog-book","forks_url":"https://api.github.com/repos/heathermiller/dist-prog-book/forks","keys_url":"https://api.github.com/repos/heathermiller/dist-prog-book/keys{/key_id}","collaborators_url":"https://api.github.com/repos/heathermiller/dist-prog-book/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/heathermiller/dist-prog-book/teams","hooks_url":"https://api.github.com/repos/heathermiller/dist-prog-book/hooks","issue_events_url":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/events{/number}","events_url":"https://api.github.com/repos/heathermiller/dist-prog-book/events","assignees_url":"https://api.github.com/repos/heathermiller/dist-prog-book/assignees{/user}","branches_url":"https://api.github.com/repos/heathermiller/dist-prog-book/branches{/branch}","tags_url":"https://api.github.com/repos/heathermiller/dist-prog-book/tags","blobs_url":"https://api.github.com/repos/heathermiller/dist-prog-book/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/heathermiller/dist-prog-book/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/heathermiller/dist-prog-book/git/refs{/sha}","trees_url":"https://api.github.com/repos/heathermiller/dist-prog-book/git/trees{/sha}","statuses_url":"https://api.github.com/repos/heathermiller/dist-prog-book/statuses/{sha}","languages_url":"https://api.github.com/repos/heathermiller/dist-prog-book/languages","stargazers_url":"https://api.github.com/repos/heathermiller/dist-prog-book/stargazers","contributors_url":"https://api.github.com/repos/heathermiller/dist-prog-book/contributors","subscribers_url":"https://api.github.com/repos/heathermiller/dist-prog-book/subscribers","subscription_url":"https://api.github.com/repos/heathermiller/dist-prog-book/subscription","commits_url":"https://api.github.com/repos/heathermiller/dist-prog-book/commits{/sha}","git_commits_url":"https://api.github.com/repos/heathermiller/dist-prog-book/git/commits{/sha}","comments_url":"https://api.github.com/repos/heathermiller/dist-prog-book/comments{/number}","issue_comment_url":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/comments{/number}","contents_url":"https://api.github.com/repos/heathermiller/dist-prog-book/contents/{+path}","compare_url":"https://api.github.com/repos/heathermiller/dist-prog-book/compare/{base}...{head}","merges_url":"https://api.github.com/repos/heathermiller/dist-prog-book/merges","archive_url":"https://api.github.com/repos/heathermiller/dist-prog-book/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/heathermiller/dist-prog-book/downloads","issues_url":"https://api.github.com/repos/heathermiller/dist-prog-book/issues{/number}","pulls_url":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls{/number}","milestones_url":"https://api.github.com/repos/heathermiller/dist-prog-book/milestones{/number}","notifications_url":"https://api.github.com/repos/heathermiller/dist-prog-book/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/heathermiller/dist-prog-book/labels{/name}","releases_url":"https://api.github.com/repos/heathermiller/dist-prog-book/releases{/id}","deployments_url":"https://api.github.com/repos/heathermiller/dist-prog-book/deployments","created_at":"2016-10-16T15:37:26Z","updated_at":"2016-12-21T17:04:23Z","pushed_at":"2016-12-21T21:29:24Z","git_url":"git://github.com/heathermiller/dist-prog-book.git","ssh_url":"git@github.com:heathermiller/dist-prog-book.git","clone_url":"https://github.com/heathermiller/dist-prog-book.git","svn_url":"https://github.com/heathermiller/dist-prog-book","homepage":null,"size":13329,"stargazers_count":250,"watchers_count":250,"language":"TeX","has_issues":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":21,"mirror_url":null,"open_issues_count":4,"forks":21,"open_issues":4,"watchers":250,"default_branch":"master"}},"_links":{"self":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2"},"html":{"href":"https://github.com/heathermiller/dist-prog-book/pull/2"},"issue":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/2"},"comments":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/issues/2/comments"},"review_comments":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2/comments"},"review_comment":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/comments{/number}"},"commits":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/pulls/2/commits"},"statuses":{"href":"https://api.github.com/repos/heathermiller/dist-prog-book/statuses/84a9fbf592cc376a41600d0d0fdc7bf18fb4dd30"}}}}
{"actor":{"display_login":"semaj"}}