Last Performance Update (for July?)

From last time, the performance and user cost was sitting at:

msbilling cost

This seems good enough...

Unfortunately, this number does not account for the end to end story where clients get changes rather than entire copies of their personalized view. Ideally, clients will connect and get an entire snapshot of the document, then subsequent updates will require a JSON merge to integrate updates. Alas, the above number represents the cost to construct a copy of their complete personalized view for every update. Outside of that measure, we then produce a delta. So, let's account for taking the difference between two versions of the view.

msbilling cost

Ouch! That's a punch to the gut. This makes sense since we are now computing the entire view, then comparing it to the previous view and emitting a delta. It is a bunch of work! Instead, what if we compute the delta as we go. That is, store a resident copy of the private view and then update it in a way which produces a delta as a side-effect. This means we avoid construction the JSON tree along with a bunch of memory allocations. This will then also avoid the costly JSON to JSON comparison.

msbilling cost

That is not half bad. We are providing more value for almost the same cost. However, this work also reverted the benefits of caching views between people which is reasonable as people may be at different points of synchronization. However, it also revealed the costs of working with JSON trees, so let's remove them and use streaming readers and writers everywhere!

msbilling cost

Yay, more work done at a lower cost is the way to go. Now, this is the last update for July, but it is also the last update on performance for a while. 95 ms is fairly good for 802 user actions over 4 users. That means we take 0.03 ms/user-action which is fast. I think this is good enough, but something else that is interesting emerged.

As part of testing, I validated that snapshots work as expected. A core value of this system is that you can stop the computation (i.e. deployment or crash) and move it to another machine without people noticing beyond a touch of latency.

The test that I did was simple. After each decision, I'd snapshot the state, then throw away everything in memory, and then reconstruct the memory and compute the next decision. This naturally slows it down, but it also illustrates the opportunity of this concept. The measurements are sadness inducing because they are bad:

msbilling cost

So, the inability to preserve state between actions is 9x more expensive on the CPU. This aligns with a view about remote caches and fast key value stores which I believe need to go. The document's size is between 75 to 80K, so this begged a question of how bandwidth changes between versions. Now, here is where is easy to get confused, so let's outline the two versions with some pseudo code.

The first version is "cmp-set", and it is something that I could see be implemented via AWS Lambda, so let's look at the client side code.


while (true) {
// somehow learn that it is the client's turn
var decisions = await somehowLearnOfMyTurnAndGetDecision()
// ask the user (somehow) to make a decision


// server routed a decision based on the person
function on_decision(player, decision) {
// download the entire state from the store/db
var state = download_from_db();
// teardown/parse the state
var vm = new VM(state);
// send the VM the message and let its state update
vm.send(player,, decision);
// pack up that state
var next_state = vm.pack();
// upload the state with a cmp-set (failure will throw)
upload_to_db_if(vm.seq, next_state);
// somehow tell the people that are blocking the progress of the game
function(person, decisions) {
// give the state to the current player
return next_state;

Now, this example has all sorts of problems, but it shows how a stateless server can almost be used to power an Adama experience. You can refer to first case study to contrast the above code to how this would work with Adama (without any hacks or holes). We can leverage the above mental model to outline two useful metrics. First, there is the "client bandwidth" which measures the bytes going from the server to all the clients (in aggregate). Second, there us "storage bandwidth" which measures all the bytes from the stateless server to some database or storage service. We can use the tooling to estimate these metrics for our example game. Here "cmp-set" refers to the above code, and we compare this to the adama version.

dimensioncmp-setadamaadama/cmp-set %
client bandwidth24 MB1.17MB5%
storage bandwidth32 MB644KB2%
% client updates that are less than 1KB0%94.8%

As a bonus metric, I also counted how many responses were less than 1024 bytes which can safely fit within an ethernet frame (1500 MTU). That is, close to 95% of the responses from the server can travel to the client within a single packet. This data is very promising, and it demonstrates the potential of Adama as a unified platform for building interactive products which are exceptionally cheap. I intend to dig into the 5% of responses which are larger than 1500 as another source of optimization, but my gut is telling me that I need to move away from JSON and lean up the wire/storage format. This should be low on my list of priorities... We shall see.

First Case Study (Chat) & Open Thoughts

The language is in a high functioning state, and it is validating the vision that I have as a madman lunatic. Today, I would like to jump ahead into the future and share the vision for how to build products with the platform that I envision. This is a useful exercise as I am in the process of defining the service beyond the series of hacks that got my prototype working. More importantly, I want to share this vision with you, and I’d also like to quickly contrast this to the past.

User Story: Chat Room#

Let us get started with a concrete use-case: a chat room. The story of this use-case is that you want to create a chat room with your friends, or you want to extend your website with a chat room feature of sorts. The key is that you want people chatting on a website. There are 3 steps to achieve this story.

Step 1: Write the entire infrastructure in Adama#

We need some infrastructure (i.e. servers) to provide the connective glue between people that use unreliable devices (they go to sleep, go through tunnels, must manage power, etc...). In this new universe, the first step is to write code within Adama, and so we must justify the reasoning for learning yet another programming language. The reasoning starts with why we write schemas or use interface description languages like thrift: it is a good practice to lay out the state in a formal and rigorous way. Adama is no different, so we must layout our state. The following code will define the shape of table.

// the lines of chat
record Line {
public client who;
public string what;
// the chat table
table<Line> _chat;

Intuitively, the above defines a ledger of chat lines within the chat room. At this point, Adama escapes the confines of just laying out state into the manipulation of state. People that connect to this chat room are able to send messages to it, and we can outline a message thusly:

// how someone communicates to the document
message Say {
string what;

This representation outlines what a single person can contribute to a conversation, and we can handle that message with a channel handler. A channel handler is a procedure which is available only to consumers of the document (i.e. the people in the chat) that are connected.

// the "channel" which enables someone to say something
channel speak(client who, Say what) {
// ingest the line into the chat, this is a strongly typed INSERT
_chat <- {who:who, what:what.what};

The above will combine the who (which is the authenticated sender) with the message what into an item within the table using the ingestion operator ("<-"). The "<-" operator is how data is inserted into tables.

What this means is that people can come together around the outlined data and contribute, but how do they read the data? Well, we expose data reactively via formulas. In this case, we exploit language integrated queries such that every update to the table will reactively update all people connected.

// emit the data out
public formula chat = iterate _chat;

This will expose a field chat to all consumers containing a list of all chat items. Note: the iterate _chat expression is shorthand for the SQL SELECT * FROM _chat. Every time the _chat table changes, the chat field will be recomputed. Now, this begs a question of how expensive this is for devices, and the answer is not at all expensive because we leverage a socket such that clients can leverage prior state to incorporate changes from the server. That is, if someone sends a message "Hello Human", then every client will get a change that looks like this on the wire:

"44":{"who":{"agent":"jeffrey","authority":"me"},"what":"Hello Human"},

This will be discussed in further detail in a future post around "Calculus". At this point, this trifecta of (1) laying out state, (2) ingesting state from people, and (3) reactively exposing state in real-time to people via formulas is sufficient to build a wide array of products. The chat infrastructure is done!

Step 2: Upload Script to the Goat Cloud#

The above Adama script is called “chat_room.a”, and the developer can spin up their chat room infrastructure via the handy goat tool.

./goat upload --gamespace chatrooms --file chat_room.a

Here, the "gamespace" term is a play on "namespace", but it is a globally unique identifier to identify and isolate the space of all instances of a "chat_room.a" experience. It is worth noting that the script defines a class of chatrooms, and there are an infinite number of chatrooms available. Once this script is uploaded, the gamespace enables UIs to create a chatroom and connect into a chatroom.

Step 3: Build the UI#

Disclaimer: This is not a lesson about how to build pretty UIs as the UI is very ugly. This is about the way the UI is populated from the server. So, with much shame, the UI looks like this:

the way the chat UI looks

And it has the expected behavior that:

  • First person clicks "Create a New Room",
  • First person shares that "Room ID" with friends (somehow)
  • First person clicks "Connect"
  • Other people paste the id into the "Room ID" box, then they click "Connect".
  • Everyone connected can then chat by typing in the last box and hit "Speak".

We will walk through how the Adama JavaScript Client Library enables these behaviors and fulfills the expectations. First, here is the HTML for that ugly UI:

<script type="text/javascript" src="adama.js"></script>
<button id="create_new_room">Create a New Room</button>
<hr />
Room ID: <input type="text" id="chat_id" />
<button id="connect_to_room">Connect</button>
<hr />
<pre id="chat"></pre>
<hr />
<input type="text" id="say" />
<button id="speak">Speak</button>

With this skeleton, let's make it do stuff. First, let's connect this document to the devkit which is running locally.

var adama = new AdamaClient("localhost", 8080);
// some auth stuff ignored for now

This will establish a connection to the server, but now we need to make the "create_new_room" button work. Ultimately, we are going to let the server decide the ID such that it is globally unique.

document.getElementById("create_new_room").onclick = async function() {
document.getElementById("chat_id").value =
await adama.createAndGenerateId("chat.a");

With this, an id will pop into the text box. Now, we need to make the "connect_to_room" room button work, and this button should populate the "chat" <pre> element. Since this is going to result in a stream of document change, we need a way to accumulate those changes in a coherent way. This is where the AdamaTree comes into play.

// first, we create a tree to receive updates
var tree = new AdamaTree();

This tree can receive updates from the server and hold a most recent copy of the document, so we can use this to attach events to learn of specific updates to the tree. Here, we will subscribe to when the "chat" field changes within the document. We will then construct the HTML for the "chat" element.

// second we outline how changes on the tree manifest
tree.onTreeChange({chat: function(change) {
// has changed, so let's recompute the "chat" element's innerHTML
var chat = change.after;
var html = [];
for (var k = 0; k < chat.length; k++) {
html.push(chat[k].who.agent + ":" + chat[k].what);
document.getElementById("chat").innerHTML = html.join("\n");

This tree now needs to be connected to a specific document, and this needs to happen when the "connect_to_room" button is clicked. So, we will do just that.

// the button was clicked
document.getElementById("connect_to_room").onclick = function() {
adama.connectTree("chat.a", document.getElementById("chat_id").value, tree);

This illustrate a core design pattern. Namely, you outline how changes within the tree manifest in changes in UI. The above shows how to update the UI when the "chat" field changes, but since the "chat" field is a list it may be prudent to update the UI based on specific list changes (i.e. append item, reordered, inserts, etc...). These specific updates are possible, but they will be saved for a later example as they introduce more DOM complexity. For now, let's focus on what happens when the "speak" button gets clicked.

document.getElementById("speak").onclick = function() {
var msg = {what:document.getElementById("say").value};
adama.send("chat.a", document.getElementById("chat_id").value, "speak", msg);

This will send the msg to the document via speak channel handler. That handler will insert data, and this will invalidate the chat field which gets recomputed. This recomputation will manifest a change for all connected people, and each person person will get a delta changing their copy of the chat field. This delta will trigger the above onTreeChange which will render the message.

This completes the UI, and it completes the usecase story.

A Time to Reflect#

At core, these three steps demonstrate how to create a working product which brings people together. This is just one demo of the future platform-as-a-service, and I am working on a few more. The key takeaway, I hope, is that every step is minimal and intuitive.

I am beginning to realize that the language is a red herring of sorts in terms of marketing. While the Adama language is the keystone for building back-ends which connect people together, the key is the platform and how it works to enable people to build. Put another way, it would be more prudent to talk about it as a real-time document store or database rather than a programming language. However, it feels like something new, and new stuff is hard to market.

It is very interesting to be in a state of seeing and believing in something, but it makes sense when I look back. Personally, I've been developing web properties for over twenty years, and I look at AWS as an inspiring enabler of doing more with less. However, a pattern is emerging where if you look at what it takes to build a web property change over time, then the following emerges.

less is more

In a sense, things are getting better on many dimensions, and the key is that our progress as a species depends on a persistence to make things better by enabling more with less. I'm a bit biased, but there is something here. I'm excited to wrestle with it.

Performance Updates & Good-Enough?!?

This update spans events over four days of joyful suffering.

Day #1#

I’m dumb. My benchmark code would randomly inject 1 ms delays due to a stupid spin-lock type concept. This was introduced quickly because there is a scheduler which scheduled future state transitions. I fixed the state transition for 0 ms delays to be... well... instant, and the world is much better. Fixing just this took our previously reported 550 to 350 ms which is a massive reduction, but it also changes the perception of the impact of the prior work.

msbilling cost

We can retrospectively re-evaluate the impact and adjust expectations. For instance, if 200 ms is pure testing overhead, then we can factor that in. That is, instead of comparing 350 to 740 (where performance began), we can compare 350 to 540 to measure the actual impact of the optimization work on production scenarios. While the testing environment saw a whooping 53% drop in time, the production environment only would see a 35% drop. While this is sad, I'm excited to see more testing happen faster.

Moral of the day: measuring is hard.

Day #2#

The day started with a focus on improving testing, finding issues, and resolving some long-standing bugs and swamp of TODOs. I was very happy with the 90%+ unit test coverage on the runtime, but the coverage improved to the point where I had to deal with the cruft and tech debt because I didn't want to write unit tests which would become bunk. It was clear that I needed to invest in sorting out the persistence model and making it rigorous, and it was time to go all in on the "delta-model". Here, I want to spend a bit of time talking about the "delta-model" and why it is so important.

At core, we must use a distributed system for durability, and a key primitive to leverage is "compare and set" which enables multiple parties to atomically agree on a consistent value. Adama was designed to exploit this, and we talk about the entire game that Adama plays by looking at how messages get integrated into a document. The below code lays out the game.

function integrate_message(msg, key) {
// download document from store
let [seq, doc] = get_document(key);
// compute new document
let new_doc = do_compute(doc, msg);
// leverage compare and set to share the new document
if (!put_doc_if_seq_matches(key, seq, new_doc)) {
// it failed, try again

Half of Adama is designed to make do_compute really easy to build with some special sauce between multiple users. An absolute key requirement for do_compute is that it must absolutely be a side-effect-free-honest-to-goodness-mathematical function otherwise the system becomes unpredictable. Now, Adama has been at this stage for a while via a series of shadow documents. The objects that Adama's code would interact were backed by a reactive object, and reactive objects were backed by JSON objects.

pure delta mode

The way this worked is that changes all flow to the JSON, and the entire role of the reactive objects was to provide a cached copy to provide the ability to revert changes. That is, the entire document is transactional. For instance, if a message handler manipulates the document then aborts a message for some reason, then those manipulations are rolled back. This ability to roll-back is exceptionally powerful, and we will see how in a moment. The work at hand was to simply throw away the shadow copies and just one giant reactive tree which could produce a delta on a transactional commit. Since JSON is the core format, we will emit JSON deltas using rfc7386. This required more code-generation and a lot of work, but it was producing deltas. But, we return to why deltas? The core reason to leverage deltas is because of physics, and physics is a harsh mistress.

Namely, what happens as document size increases with a compare and set system?

  • The time for both get_document and put_doc_if_seq_matches increase due to network cost.
  • Whoever is executing get_document must deserialize, execute do_compute, then serialize for put_doc_if_seq_matches; these all cost resources which grow with document size.
  • As time increases, the probability of conflicts emerges for put_doc_if_seq_matches which adds more time which starts to cascade with more time and more cost.
  • Oh, and people are constantly downloading the document, so the resources on what-ever shard is providing get_document is undergoing more contention to simply share updates to other people. (And, how they know when to update is an entirely different system usually using pub/sub

There be dragons in all services, but the short answer is these compare and set services work well for small fixed objects. These systems tend to have caps on what their document size is. For instance, Amazon DynamoDB has a low 400KB limit, and I almost guarantee that there is a frustrated principal at Amazon who thinks that value is too high. Now, there are a variety of ways of working within these limits, but they tend to shift the cost to more resources especially on the network. Instead, Adama proposes a core shift towards a more database-inspired design of using a logger.

Databases have the advantages that their updates can be replicated rather than direct data changes, and this enables Databases to become massive! This is the property we want to exploit, except we don't want to describe changes to the data. Adama's role is to deal with user messages, integrate them into the document in a natural way, then emit a data change seamless to the user. This is game changing, and the key is to understand what runs on which machine. Abstractly, I see a mathematical foundation to be exploited.

pure delta mode

This is the foundation for an entirely new service, but it requires clients to maintain state. That is, clients use must leverage stateful practices like using a WebSocket. Typically, stateful approaches have short-comings as application services tend to have gnarly problems, but Adama overcomes them. Let's explore what integrate_message becomes in this new world.

function integrate_message2(doc_reactive_cache, msg, key) {
// pull any updates into our local cache
sync_document(doc_reactive_cache, key);
// compute a delta (half the purpose of Adama).
// -- 1: do compute with side-effects
// -- 2: roll-back side-effects
delta = compute_prepare_delta(doc_reactive_cache, cache, key);
if (!append_delta(key, delta)) {
// well, we already failed, so let's maybe check back with the caller?
// maybe the caller has more messages to send?
// maybe the need for the message got cancelled based on new data?
// maybe just convert msg to [msg]? maybe and get some batching love?
// lot of opportunity in the retry here! we can even exploit flow control!
integrate_message(doc_reactive_cache, msg, key);
} else {
// pull the commit down along with anything
sync_document(doc_reactive_cache, key);

This has much nicer physics. As the document size increases:

  • time is bounded by changes inflight
  • the network cost is proportional to changes.
  • the CPU cost is proportional to changes.
  • the consensus is proportional to data changes.
  • as conflicts emerge, messages can be batched locally which reduce pressure to minimize conflict
  • batching locally enables us to exploit stickiness to optimistically eliminate conflict and further drive down cost.

And this is just what happens when using a reactive cache which can be blown away at any moment.

With the physics sorting out as way better, we must return to the decision to leverage a stateful transport like WebSocket because it may be a horrific idea as stateful services are exceptionally hard. The moment you have a socket, you have a different game to play on the server. This new socket game is mucher hard to win. Now, it is very easy to get started and achieve impact. However, the moment you consider reliability you must think about what happens when your stateful service dies. This is the path for understanding why databases exist. It's so hard that there is a reason that databases are basically empires!

In this context, using a socket is appropriate because it has one job: leverage the prior state that the connection has in a predictable way. For devices to the server, the socket is used simply as a way of minimizing data churn on the client. For instance, the "stateful server code" is simply:

function on_socket(connection) {
var doc = get_document(connection.key);
connection.write(doc); // the first element on the connection is the entire document
while(sleep_for_update()) { // somehow learn of an update to the document
var new_doc = get_document(connection.key); // fetch the entire document
connection.write(json.diff(new_doc, doc)); // emit updates as merges
doc = new_doc;

Now, there is room for improvement in the above with Adama as the language which generates document updates, but the core reliability is understandable and not very complex. This is the key to leveraging something like WebSocket without a great deal of pain or self-abuse.

Day #3#

Holy crap, I’m dumb. I am just not smart enough to be doing what I am doing building a reactive differential programming language database thing. Found two big issue which invalidate all of my work and life... in a good way.

First up, and this is really bad... I wasn’t actually deleting items from the tables. I was just hiding them and not removing them from the internal tables which means most of the loops were filtering dead stuff. No wonder things were going slow. Fixing this alone dropped the time to less than 120. This was unexpected, but it is worth noting that I wasn't investigating performance at the time. Instead, I was investigating the correctness of the "delta-model", and there was something rotten in the mix. Testing the delta model requires accepting a message, producing a delta, then persisting that delta, then throwing away all memory (effectivelly turn the tiny server off), then rehydrate the state from disk. The goal is to produce a model where servers can come and go, but users don't notice.

do users notice

Well, as a user, I was noticing. It turns out there was a break in reactive chain, and this was the second issue. I was up until four am in the next day...

Day #4#

Woke up, fixed the issue. It's amazing how sleep fixes things for you. An interesting observation was that testing the delta-model was showing a bug in the prior assumption validity of the test; that is, I found a deeper bug outside of my immediate changes. Unfortunately, that means my test case is no longer congruent with the previous test runs (the number of decisions dropped from 798 to 603). I've checked the delta log, and the new version appears correct at the point where the fault happened. Because it is doing the right thing now, I had to find a new one. The new test case has 802 decisions, and it comes in at

msbilling cost

Based on decisions, this feels close enough to call it a good enough test case given the results from day two were in the same ballpark. This means that the production environment would experience a 540 --> 120 time drop (78%) while the testing environment would have experienced a 84% drop, and user satisifcation would be up due to less bugs.

While I'm still not done dealing with all the fall-out of the delta model, I do have to wonder if this is good enough. Well, I know I can do better because in this world if I turn off client view computation, then the time drops to 49 ms which gives me hope that I can optimize the client view computation. However, I think for the day and probably the month, this will be good enough... or is it? Honestly, I'll probably explore creating client views with streaming json.

Performance Funday

A non-productive theme for July is to jump into performance and measure a few things. The hope is that this search will produce some low-hanging fruit that I can exploit, and I also intend to validate correctness on many things since there are some slap dashing stupid stuff. A core reason for the urgency beyond being interesting work is that I want to utilize permutation testing as a way of finding novel test-cases. Given that it took a bit over half a day to simulate playing 1.2 M games, I would like to be able to cut that time down.

Test Setup#

I am going to leverage the current game prototype which comes in at a massive 4.8 KLOC, and the goal is simulate random players playing a game. To factor out the randomness, I’m going to seed the random number generator such that the game play and decisions are predictable. I tweaked the seed parameters until I found a meaty enough game to stress the system.

This meaty game will be played 101 times, and the results from the first test will be thrown away as it is heavily influenced by the JVM warming up. Each test afterwards will produce these data columns

  • Time: proxy measure for CPU (and memory induced GC pressure) within a single thread.
  • “Billing Cost”: number proportional to the amount of work done (the language bills by the statement and a few other things)
  • Decisions: number of decisions taken by all the agents within a game

It is worth noting that “billing cost“ is expected to remain constant within a single test run, and the number of decisions is expected to remain constant over all runs because it is a measure of correctness. Decisions must be fixed at 798. Over those 100 runs, the average time will be a sufficient measure of performance. I intend to eyeball variance, but I leaning on an average to factor out GC cost. With all this said and done, the initial data is thusly:

msbilling cost

That is approximate 1ms per game decision. This actually feels super slow, and as a secondary goal of this work is to build tools to dive into issues. My intent during this day is to just address the language and not push back on the user-space changes.

Exploit Primary Key#

Every record has a primary key called id which is unique and an integer, and it is fairly common to leverage this to find items by primary key. Since the only way to get access to data within a table is via a language integrated query, we must contend with the query syntax. The first task was to analyze where expressions to extract associations mapping the primary key to an expression. The initial algorithm for this is simple, and I'll write with pseudo-ish-code here (I'm actually using Java, but it is too verbose):

function extract(expr):
if expr is Parenthesis:
return extract(expr)
if expr is BinaryOp(&&):
result = extract(expr.left)
if !result:
result = extract(expr.right)
return result
if expr is BinaryOp(==):
if expr.left == Lookup("id"):
return expr.right
if expr.right == Lookup("id"):
return expr.left
return null
return null

This identified many cases where the primary key was part of the where clause, and the results were.... disappointing. The billing cost went down 2.5% while the time cost went down only 1.4%.

msbilling cost

Ok, this is going to be a slog.

Direction Seeking: What if we don’t update client views#

The tool at hand doesn’t really need to see the individual view per agent, so as a method of developing a direction we can experiment and simply turn that feature off and see what happens. This enables a quick way of developing a sense of where time is worth spending. We do that, and the data is revealing.

msbilling cost

This shows potential in that the billing cost is overblown and the client views represent close a third of our CPU cost, but billing was reduced by a whopping 70%. This fundamentally requires investigation. Now, this is not the way, but it gives a tingle to explore. Please ignore the above data.

Cache Record to Json#

In thinking about how to optimize client views, we can exploit caching of viewable records between the four agents. However, this requires a consultation with each record’s privacy policy. Statically, we can devise a very simple predicate to eliminate the need to compute per-user views. A record's per-user view can be cached if:

  • Has no bubbles
  • Has no visibility requirements.
  • The privacy for each field is either public or private
  • The fields are all primary data (i.e. ints and strings) (i.e. neither records nor tables)

With this, we can stash a copy of the JSON within the record and let record invalidation blow it away on change. By leveraging the reactive elements, we not only cache between viewers but also over time as well. This result in new data.

msbilling cost

This is very encouraging as the billing cost has now been reduced by 20% and CPU cost is down 12.4%. In terms of the goal, that’s over an hour of time saved in the experimental test.

Quick Experiment: Turning Off Code Coverage#

Currently, the document keeps track of every single statement which gets executed in a giant list... The question at hand is how much that costs.

msbilling cost

This is slightly exciting for production as this takes us towards a 16% CPU reduction, but this is a requirement for the testing I hope to achieve. As I hope to guide agent decisions towards maximimzing code coverage, I must turn this off... for now. Please ignore the above data.

Direction Seeking: Bad Indexing the Tables#

Indexing is the bees knees, so let’s introduce indexing to our tables!

This is not an easy endeavor, so we first set out to measure opportunity. We do that by doing half the hard work now, then exploit that work to measure and validate correctness. What we measure is the potential to do good work if we finish the other half of the hard work.

First, we have to leverage and extend the analysis work done via extracting the primary key and generalizing it to any field. This was added to the code-generation such that a where could generate a flat array of which columns map to which value. Second, each item must reveal their data in an easy to consume way. Third, we must measure how effective the where cause could be enhanced with indexing. This work enables a very simple algorithm to test

* @param clause an integer array mapping columns to values [col0, testValue0, col1, testValue2, ..., colN, testValueN]
* @param value an integer array represent a particular item's columns [value0, value1, ..., valueM]
* @param effectiveness how effective a column was at rejecting the item
private static boolean slowTest(int[] clause, int[] value, int[] effectiveness) {
boolean result = true;
for (int k = 0; k + 1 < clause.length; k += 2) {
if (value[clause[k]] != clause[k+1]) {
result = false;
return result;

Now, this code is not great for a variety of reasons, but we can run it prior to executing the where clause and measure changes to billing cost. Well, data came in, and it was both suprising and not so.

msbilling cost

A 10% CPU bump (yikes), but a 83% reduction to billing cost (woah). OK, this is very pro-customer, however this does not help me. It is however encouraging that if I roll up my sleeves, then I can get some better results.

Index all things?!?#

The challenge of indexing in a reactive system is not paying the implicit insertion cost. That is, stuff will change, and you don’t want to constantly insert and remove items. You need to be a bit lazy, and for indexing this requires some book-keeping and allowing some slack to emerge. Each column must have its own index, but when things change they must be either be removed or included in a catch-all bucket since the indexing is indeterminate in a lazy system.

private final ReactiveIndex<Ty>[] indices;
private final TreeSet<Ty> unknowns;

The key is that the combinatation of column specific indicies plus this catch all bucket form a super-set of the right answers you seek, and the hope is that the resulting set is smaller consideration pool. First, we index everything and measure the overhead:

msbilling cost

Yikes! It is already adding cost to just index the data. However, we have yet to use the data. One more blind trial, but let's compute the needed super set.

msbilling cost

Oh no, this is not trending good at all! Let's use it.....

msbilling cost

I am Jack's sense of disappointment. OK, this is proving to be my white whale. There are many problems with the approach I have taken on this... Part of the problem is that I’m indexing every enum, integer, and client variable. Pareto is proving a relevant observation, so I’m going to need to take a break... Several hours pass

I’m going to restore the code I used for the bad indexing, then put it behind a condition and introduce a DocumentMonitor. The role of the DocumentMonitor is to stream data out to me which I can use, and I have a flag called “measureTablePerformance” which will use that bad code in special circumstances.

public interface DocumentMonitor {
/** should the runtime measure table performance */
public boolean measureTablePerformance();
/** emit a single datapoint about table performance */
public void recordTablePerformanceInstance(
String tableName,
String colummName,
int total,
int effectiveness);

With hope, the if statement doesn't regress the performance...

msbilling cost

It's basically the same, so let's use it to emit some data, collect that data into a table, and then review the table.


Clearly, I want to exploit the skillcards table since it is highly rejective. Out of 6.7M tests, 5.2M could be quickly rejected via an index. This is great! We should exploit that, so let's do it. This requires a bunch of working like: upgrading the parser, updating the code generation to present the indexing information to tables, and then upgrade where clause code generation to build the needed set. Given that the last code was mostly thrown away due to complexity, this is going to require care... _Even more hours pass

msbilling cost

OK... seriously. All that work for an additional 2% in CPU reduction. Sigh. On the bright side, the billing is now more customer-friendly and is down 77%. If the where clauses were more expensive, then this would be a very productive thing, so we will keep it as it is customer-friendly feature that encourages better focus on more controllable things by the customer.

Fixing a bug in the reactive tree#

As part of this work, something felt off as to why so much computation was happening in the first place. This triggered an audit into the code, and I had to rethink a few things from core first principles. At hand, how formulas were being computed was done poorly due to sloppy mixing of invalidation and dirty signals. The core two principles at play were:

  • invalidation alwayss flow from data down to formulas
  • dirty signals flow up from data to root

invalidations and dirty signals

This diagram became crucial for investigating each class and making sure it conformed to the principles. All but two of the classes behaved, and the one that did not behave had a giant TODO on it. Fixing that TODO and the other class caused the system to behave, and produced new data.

msbilling cost

At this point, 25% of the CPU has been reduced and 82% of the billing cost has been reduced.

Until next time.#

I'll take 25% as a win for now, but I want to invest in tooling to provide better insights. There is some super dumb code within the prototype at the moment because the focus then was to ship the game in a workable form.

June went by fast! Woah!

I’ll be honest, I didn’t get as much as I wanted done beyond a bunch of clean-up on the language and develop a few new language features. I am however much happier with the state of the world now, but I’m avoiding a few things like deprecating some dumb ideas.

I finished going ham on the parser. Rewriting the entire parser from scratch by hand required rebuilding my trust in it, so I set out to get test coverage on the parser and the type checker. The core language has 100% test coverage, and this process uncovered many bugs. It further required resolving many TODOs within the code. The parser swap was a deep change, and while I’m very happy with it and the correctness of the language with my over 1,500 tests; the time has come to polish the error messages and align the character positions with the errors to be meaningful. This is the way for July.

Before I went ham on the parser, I made progress on simulation. I simulated 1.2M games over night. I let all my cores go, and I discovered that complete games could be played in under a half a second. The purpose of these simulations were to randomly play games looking for dead-ends, crashes, or game-ending problems. The time per game-decision was about 2.1 ms which is exceptionally high. Performance being a non-goal meant I’d move on.

Something amazing happened after going ham on the parser, fixing issues, eliminating some hacks, and improving the type system. The simulation performance tripled and now the time is about 0.7 ms per game-decision. w00t. I hope to spend a touch of time in July optimizing performance a bit because it is fun, and I hope to double the performance again.

Going HAM on the parser with next level testing

Finding the balance between what to work on is a challenge when there are so many interesting problems ahead. Testing the back-end for the current game has proved to be a challenge due to the entropy involved, so I’m thinking about ways of building tooling to corral that complexity and chaos.

However, the game works, but I have yet to reach the reality of the first milestone of playing with friends (UI sucks, afraid of a game-stopping bug). I am going to focus on improving the core in two ways. First, I want to improve the error messages. Second, I want to bring real-time code coverage into the picture as part of the test tooling.

I started with ANTLR to do the parsing and help me build the trees backing the language primitives. However, I started to get frustrated with what ANTLR does with white space and the error messages it produces. While that is relatively minor, it also requires me to rethink all my trees to accomplish some goals. For instance, I want to make it easy to do refactoring and code completion. I also want to support LSP to bring comments on field via the hover mechanism. In using ANTLR, I have found truth in some wisdom from why others recommend not using parser tools.

The objectives of the new parser are thusly:

  • Have a unified way of thinking about comments which can annotate any and everything
  • Have the parser become an ally in how to format the code
  • Have great error messages
  • Make it easy to associate environments to the token space such that code completion queries are fast and relevant.
  • Be fast (it is already 20% faster)
  • Fix some keyword issues such that things which identifiers are forbidden versus not.
  • Achieve 100% code coverage on the parser
  • Fail on the first error, it is simply better that way

With the new parser, I will have plenty of information to think about code coverage at the character level. With code coverage and the code indexed with comments, I can build a tool where the test cases are generated for me and the transitions are generated to achieve code coverage. The aim is to use AI techniques to minimize the total number of automated tests to simplify the validation.

Now, this requires more thought and more words to elucidate, but imagine having a UI which shows you the raw state, the code with comments that is being tested, and the related state change of running that code. This can be certified as a good and right state change (by potentially multiple people), and this test can be saved for posterity and re-ran later. However, if changes happened, then those changes can be validated as either new data changes, loss of a data change, a different data change and require new certification.

Existing tests are fed in to establish a base line code coverage, and new tests can be generated such that code coverage is maximized with minimal test certification. For instance, the introduction of a new card could require several test cases to be randomly generated such that the shuffling of the card happens early. Only the test cases which extend code coverage need to be stored and certified.

It feels exciting that I’ll never need to mock or write test code ever again since the goal of testing is primarily about reducing entropy and maximizing determinism.

How this all started from building a custom browser

Conceptually, a user interface is a simple thing. It is a pretty and delightful picture which makes it easy to understand and interact with a product. That's it.

Since Adama is a programming language for board games, it stands to reason that Adama does not exist in a vacuum and it must be workable with existing UI technologies. That is, it must sanely integrate with a variety of frameworks to achieve some measure of success and be usable beyond my myopic view of reality.

When it comes to modern day application building, I am an old man screaming from my porch for you damn kids to get off my lawn.

An interesting point of history is that my recent work on board games actually started using SDL and then eventually Skia with C#. I was trying to build a new style of browser where (1) a single socket was the only way to get data and send messages, (2) there is exceptionally limited client side logic to eliminate abuse, (3) anti-entropy protocols would reconcile data between client and server, (4) the browser was 100% reactive to data changes, and (5) the server was in complete control because "the network is the computer". Now, there is a lot to unpack here, but the point is that building a new style of browser is a monumental task within itself.

The reason for starting a new browser is that I feel the web is a complete shit-show, and I hate building web products. I hate that your stupid website runs code on my machine. I also hate how a lack of privacy is a given in today's world. Remember, I'm full of hate.

Putting aside the bucket of rage I feel when using the internet, I wanted to bring board games to mobile devices. That was the mission. My hope was to ship a simple binary which would utilize a single secure socket to do some magic and let the game play happen like an efficient remote desktop protocol.

Unfortunately, when you start building new UI frameworks with new idioms and low-level technologies, you kick off a massive empire building project which will require support and tools. Once again, I was shaving a Yak and building a new empire in praise of the glorious understanding that I have acquired about these stupid machines. I wish I had realized this before getting a working UI editor sort of done. sigh

The socket was a key thing to focus on. I prefer raw sockets because they are stateful and conversational. For board games, they are essential because of the inherent complexity of communication between players. The socket simplifies this because you can use the socket to mirror the server state, and all the complexity can be held within the single server.

Key reason for socket

The moment you have all state within a single server, the challenge of shipping a complex product is several orders of magnitude less due to practically zero failure modes. There is just one tiny problem... The reliability of a single server in today's cloud with crazy orchestration and almost constantly induced failures is not great.

Ignoring that tiny problem, I persisted since I had built a prototype tiny browser and if I control the hardware then I could probably be ok (right?). There I was building my favorite game with node.js as my back-end, and I had finally made some decent progress on the game. The usage of a socket and some of the new UI idioms were proving fruitful. However, the server-side complexity became exceptionally overwhelming. Board games are non-trivial endeavors.

This is where the impetus for Adama was born. There were three key mission questions to drive. First, can that pesky single server limitation be overcome where machine failures are handled gracefully without user impact. Second, are there useful primitives which reduce the total complexity. Third, what essential truths were learned during from the simplified UI idioms.

These first two questions will be addressed at length in the future, but the last question however gave pause. Systems do not live in an isolated vacuum, and it is the role of the system to make itself useful beyond its immediate peer all the way to the user. Afterall, Distributed systems are a UX problem, so we must operate on primitives which are useful to the UI and the UI developers.

First, we study the UI idioms which the toy browser used. They were straightforward, have been incorporated in the prototype of Adama:

  • An Adama server can only receive messages from clients of two core types.
    • The first type is a free form message like "say hello" which has no rules associated to it. It's only for the pesky humans.
    • The second type is a response in request-response where the server asks the client a question (which piece do you want to move, where do you want to move it). This is the magic for implementing the board game logic in a sane way, and also the secret for enabling AI. This will be written about at length in the future.
    • Note: there is a possible third type where the client may send a request to Adama, and Adama will respond, but that is open to debate. It feels natural (and may be useful outside of the current domain), but it introduces dealing with the failures of the RPC. Instead, messages are stored in a queue on the client side and must replicate to the Adama server with exactly once semantics (i.e. at least once with deduping) Adama must keep the client state up to date and be consistent
  • The entire application state is a giant object represented by JSON
    • An Adama server can differentiate the state and keep the client up to date with json merge (rfc7386) for the win.
    • The UI must then process a stream of state differentials which are congruent to the initial payload (i.e. they have the same shape and form, but differentials have vastly less information)

Ideal User Interface

The entire application state being a giant JSON is reminiscent of Redux and the notion of an application state container. Now, this has the property that the UI simply needs to react to changes of a single object. In the toy browser, the role was to simply render the scene and then index the scene in a way to convert interactions into messages. With the browser, this requires work to expose new idioms, and this is where I am at. Since the JSON is predictable, there is a maybe new (or not) concept of an "object sieve subscribe".

var sieve = GOAT.CreateSieve()
GOAT.SieveSubscribe(sieve, wrappedCallback);

The implementation of the above is basically to implement json merge (rfc7386), and then publish out changes as they happen by walking a parallel object callback structure (ie. the sieve). We can gleam a basic idea of how this works with single example.

GOAT.SieveSubscribe(sieve, {'turn': function(change) {
[ "The turn has changed from ",
" to ",
document.getElementById('turn').innerHTML = change.after;
GOAT.SieveMerge(state, diff, sieve); // <- powers the entire engine

This example shows an interesting idiom where updates on the UI are ONLY derived from the update stream. There is no global re-computation, and no giant reconstruction for small changes. This property was important for the toy browser because I was aiming for a battery efficient engine where only updates would refresh the screen rather than periodically polling the scene.

However, there is a small hitch. JSON Merge (rfc7386) does not handle arrays well, but this can be overcome by constructing a new merge operation which enables array differences. This requires the server to craft and embed meta signals in the delta, so that's what I am working on at this very moment until I got distracted by my thoughts. This will be described in more detail at a later date.

The core observation that I have had through-out this journey is that when back-end and front-work together, amazing properties are to be had. In this case, a small change from client to back-end results in a small change from back-end to other clients using a small amount of network. When clients learn of changes, they update proportional to the change at hand. No excess. No fuss. Just niceness.

Progress is Slow, May 2020 Update


I forgot how much work there is in building a programming language, but it is super fun. So here we are in May of the remarkably interesting 2020. I am coming out a slump of depression (I think) from this world-changing covid-19, and I recently made good progress towards the first milestone.

I am lurching forward ever so slowly every weekend I invest in this madness.

The first milestone is, fundamentally, a real game. Afterall, if this thing cannot ship real online board games, then it is a failure. The good news is that I am testing a real game, filling in missing rules, adding content, fixing bugs, re-reading the rule book, and working on the UI. I do not expect much from the UI for a game I do not intend to release (friends only due to licensing issues). The key thing is that I am suffering my language while I make progress on a product rather than being stuck in the infinite meta-game of improving the language.

It is a remarkable feeling to have over 3,000 lines of code in my own language.

This first milestone will be a success when I play a few games with people I know, and I am getting closer to this every weekend. The real question is what happens after this milestone, and this is where I need to find a good balance between playing the product-game (i.e. shipping real games) versus the build-the-empire (i.e. the meta-game of developing the programming language). What is a successful strategy?

This is something to think about during May, but one thing on my mind is that I must have a ruthless focus on shipping games rather than focusing on meta-problems. “Write Games, Not Engines” is particularly good advice. I am finding that I’ve solved a sufficiently hard problem with my language to justify its existence because I’m using the language to do exceptionally complex things, but I must resist the siren’s call to improve the language because that is an never-ending task.

So, my current premature attempt at a strategy is:

  1. Fix bugs in the language which are show-stoppers.
  2. Ship a game
  3. Do a retrospective after shipping a game, write about what was good versus what was awkward.
  4. Pick exactly 3 issues to improve within the language, and do them
  5. Goto 2

First Announcement

Welcome, welcome, welcome...

This is the first update on the Adama language project!

I finally have set forth on the journey of telling people about my latest passion project. Surprise, it's a programming language! However, it is not a generic programming language, and I want to make this exceptionally clear. It's a domain specific programming language meant for board games. Yep, that's right! Board Games!!!. However, I have discovered this language has some very interesting properties which make it broadly applicable, and I have a vision for a new type of infrastructure!

Since there is not much to share about the project at the moment, and I am really just filling in the blog so I have some content. I'll share a bit about who I am and rant a bit. Maybe it will be entertaining! Let's see.

My day job is one of those "technical architects", "engineering leaders", and sometimes "code machine". I recently gave myself the title of "Dark Lord of Infrastructure Engineer". That is seriously the title on my business card, so it is definitely legit, right? Well, it simply means I've succumbed to the dark side, and I don't mean management. Instead, I find myself more driven by hate than anything else.

I hate.

I hate bad infrastructure.

I hate leaky abstractions which become infrastructure.

I hate unreliable infrastructure.

Seriously, I hate the way we define Infrastructure via web services, but what other choice is there? This is a serious question.

I also hate having to read a long ass list of products and realize that my core option is to buy stupid shit rather than build my own stupid shit where I have control. I hate buying shit because buying creates hard boundaries which more often than not requires some kludge or hack to make work well. I value reliability, and I believe reliability only comes from simplification where less is more. And, I don't mean less stuff to buy, but less total stuff period. However, simplification is exceptionally hard and extremely expensive for a multitude of reasons.

I'm that fucker that shaves the Yak, and I have issues. Worse yet, I sometimes will allow myself to be the enemy of the good and seek perfection. I have issues. After-all, one doesn't set forth to build a programming language unless one has serious fucking psychotic issues and hatreds!

The interesting thing however in that the psychotic issues which drive me to write this language has given me a deeper appreciation and understanding of the science in the field. In a way, I've got closer to the root of things and how we build, and I see a different evolutionary branch to take. I believe I've discovered something, and I intend to pull that thread to build a new glorious empire!

Adama is the first step in building out my glorious empire dedicated towards building a new web and redefining the landscape for how products are built, and it all started with the desire to make board games easy to build.

I hope you enjoy reading what I write, and I hope you eventually decide to drink the Kool-Aid about Adama.

Thank for your time.

And, if you hate it, then that's ok. I get it.