Monthly Archives: January 2017

Fantastic Bugs And Where To Find Them

Last Friday we encountered a bug in our codebase whose origin was of such a peculiar nature, and whose eventual resolution proved so instructive, that I thought I would record it here.

First, some brief background. EndlessOS is built for two different computer architectures: x86 and ARM. With a few notable exceptions, personal computers generally run x86, while tablets and smartphones run ARM. In an effort to bring down the cost of PCs (ARM chips tend to be cheaper) Endless has released a desktop computer running ARM. Since the chipsets are designed differently, compilation – that is, the process by which we translate source code to machine code – must happen separately for each architecture. Our OS, with all its accompanying apps and tools, must be built twice, and, of course, tested twice. However, application code, living as it does in the cushy land of user space, usually does not exhibit different behaviour when running on ARM versus running on x86. In fact, only if you are doing low-level processor instructions, such as bit manipulation, should you even care what chip architecture you are running on. It was, therefore, to our surprise (and, indeed, horror) when we discovered, late in a release cycle, that a number of our apps had been shown to work on the x86 machines, but not on the ARM machines. The QA team reported that upon opening one of these problematic apps, the user would never be able to access a subset page. Without going into too much detail, suffice it to say that the data in our apps is organized into ‘sets’ and ‘subsets’; clicking on the title of a subset ought to take you to the subset page.

Our apps are built with a homegrown framework we have at Endless called the Knowledge Library. The framework provides a number of components, or ‘Modules’, which you can use to rapidly build complex, data-driven applications. Apps are built in Facebook’s Flux paradigm, complete with a dispatcher, history store, and of course, views in the form of GtkWidgets. I knew (because we had built it) that the module responsible for transitioning between pages in an app was the Pager. Examining the Pager code, we found the line responsible for displaying the subset page:

if (SetMap.get_parent_set(item.model) && this._subset_page) { 



If the subset page wasn’t showing up, it meant that one of the two expressions in the if condition was evaluating to false when it shouldn’t do. The second condition this._subset_page simply checks to see if you have a subset page at all in your app, which I knew we did. The first condition queries the SetMap – an in-memory graph which maps relationships between set models in the database – and asks if the parent set of the model in question is defined. In essence, this is equivalent to asking if model has a parent set – if it does, then we know that the model is a subset, and that therefore it is appropriate to show the subset page. We suspected, then, that something was up with the contents of this SetMap – specifically, we guessed, based on knowing how SetMap was written, that it had no data in it at all, and was just mindlessly returning null for any and all set queries we gave it.

We decided to take a look at where SetMap was getting its data from, and found this function:

initialize_set_map: function (cb) {
        limit: -1,
        tags_match_all: ['EknSetObject'],
    }), null, (engine, res) => { 
        let results;
        try { 
            results = engine.query_finish(res); 
        } catch (e) { 
            logError(e, 'Failed to load sets from database'); 

The relevant context here is that the Engine retrieves data from our database according to the parameters of the query it is given. The query takes the form of a JSON object, and, in this case, is simply:

    limit: -1,
    tags_match_all: [‘EknSetObject’],

What we’re saying here is fetch me content tagged as ‘EknSetObject’, and don’t impose a limit. Now, if our hypothesis was correct, and the SetMap was empty, that meant that this query was returning nothing. However, we knew that we were seeing sets on the home page, and the query which returned those sets was remarkably similar:

    limit: limit,
    tags_match_all: ['EknSetObject'],
    sort: Eknc.QueryObjectSort.SEQUENCE_NUMBER,

Both queries were asking for sets, but one was getting some and the other was getting none. What was different between them? Well, one difference we can see here is that the home page query requests its results to be sorted by the SEQUENCE_NUMBER key. Our Xapian backend database allows for sorting by predefined keys, and the SEQUENCE_NUMBER key describes the order in which models were added to the database. Having the results in that order is important when showing them on the home page, but in the case of a SetMap, where data isn’t going to be arranged linearly anyway, sorting is obviously irrelevant, so no sort field is included. In any case, whether data is sorted or not shouldn’t affect the quantity of said data that is returned, so we dismissed that as being the source of the problem.

What about that limit field though? Limits certainly do affect the quantity of things returned, and that -1 numeral seemed particularly suspect. I knew we had been using -1 as a special value to indicate ‘no limit’, but couldn’t quite recall how that worked. Just as a test, we changed the limit to a positive value, 10, and ran the app again. The bug was gone! The limit field was indeed the culprit, but our investigation had now only just begun. We certainly couldn’t leave this value at 10 – remember we wanted all sets returned, not just 10. Furthermore, this discovery seemed only to raise more questions: we had been using -1 to denote ‘no limit’ for many releases now, why were we only seeing that it was problematic now? If -1 was a problem for the query to handle, why was it not throwing an error, why instead return no results? And, perhaps most troublingly still, why were we only seeing this bug on the ARM architecture machines?

We dug more into the use of this limit field. Along with the rest of the query, the limit field eventually gets serialized into a JSON string and sent over an HTTP bridge to the local Xapian database server. Once on the server, which, unlike the app, is written in C, it gets parsed with the following line:

limit = (guint) g_ascii_strtod (str, NULL);

Here we were parsing the limit string as a double (the g_ascii_strtod() function converts strings to doubles) and then casting that double as an unsigned integer. Several things seemed awry at first glance: why were we parsing this limit field as a double, when doubles are meant only for storing floating point numbers? And, having parsed it as a double, why then cast it as an unsigned integer? Moreover, if it is meant to be an unsigned integer, how is -1 a valid input?

We pulled this line of code out into its own source file, ran it to see what happens when str is -1:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <glib.h>
#include <stdint.h>

main (int argc, char *argv[])
    unsigned int limit = g_ascii_strtod ("-1", NULL);

    fprintf (stderr, "limit := %u\n", limit);

    return EXIT_SUCCESS;

Running on my intel machine this program printed out 4294967296, more commonly known as 232 – the maximum value expressible in a 32 bit integer. Aha! So here is where the -1 made good on its promise to be a ‘special value’ for fetching all sets. By casting it from a double to an unsigned int, we were exploiting the Two’s Complement method of storing integers to ‘transform’ the same binary number (in this case, 32 consecutive 1s) from a ‘-1’ to MAX_UINT. Setting the limit to be such a large value was effectively the same as saying ‘impose no limit’, and that is how we would get all sets returned.

We ran the same code snippet on ARM, and lo and behold, it printed out 0. We knew now that it was this line suffering from architecture dependent behaviour. But why? Why didn’t the ARM machine also exhibit the integer underflow trick? It turns out that, in the C programming language, underflowing an unsigned integer, far from being a clever trick, is in fact undefined behaviour. I had always vaguely been aware of this fact, but had not, until last week, quite appreciated the import of what that term carries. What I had understood about integer underflow, and other undefined behaviours, was that they were inadvisable, bad practice, perhaps even that they would trigger an error in certain cases. The truth is much more sinister than that, for the C spec is written not so much for you, the C programmer, as it is for the compiler. How operations behave and what constitutes valid syntax are built into the compiler. What then, does the C spec say about ‘undefined behaviour’:

Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.

This blog post by a CS professor at the University of Utah provides an excellent overview of undefined behaviour in C and C++, but the bottom line is that once you invoke undefined behaviour, all bets are off: the entire program becomes meaningless. As long as it adheres to the explicit rules in the spec, compilers have enormous freedom. We violated those rules the moment we included an integer underflow. At that point the compiler could do whatever it pleases and still claim to be a valid C compiler. It could have refused to compile; it could have compiled and then promptly crashed; it could have compiled and then printed out the complete works of Charles Dickens to stdout. All of these are valid executions of the program because the program has now lost all meaning.

One might be tempted to think: ‘but surely only that single line was invalid. Even if it does do something bizarre when it reaches that line, shouldn’t the rest of the code up to that point function normally?’ This objection (which I myself raised) has both a theoretical and a practical answer. Theoretically, the answer is simply no that’s not how computer languages work – once you include undefined behaviour, the whole program is said to be meaningless. Furthermore, practically speaking, the notion of ‘reaching that line’ itself betrays a misunderstanding of how the compiler works: a compiler is at liberty to rearrange lines of code (which it does indeed do to optimize performance) provided such rearrangements will not have observable side effects on the execution of the program. Of course, a real world compiler probably won’t rearrange things such that that integer underflow line screws up the rest of the program, just as a real world compiler probably won’t print out the complete works of Charles Dickens when you try to divide by zero, but the point is that you can’t assume it won’t do those things, and there are lots of things it could do that lie in between that and normal execution. It could, for example, when it sees an undefined integer operation, choose to assign a zero value to the unsigned int. This is what apparently did happen on our ARM machines, and the reason why might have something to do with the ARM processor’s ability to store memory in both big-endian and little-endian format. In any case, when we consider the infinite domain of options that our illegitimate operation gave the compiler license for, returning zero now actually seems not unreasonable.

As is often the case, once we understood the problem, the patch itself was quite simple. Given that we were already late into the release cycle, the aim was to keep the diff on this patch small, so we simply added a check for the negative value

 /* str may contain a negative value to mean "all matching results"; since
   * casting a negative floating point value into an unsigned integer is
   * undefined behavior, we need to perform some level of validation first
    double val = g_ascii_strtod (str, NULL);

    /* Allow negative values to mean "all results" */
    if (val < 0)
      limit = G_MAXUINT;
      limit = CLAMP (val, 0, G_MAXUINT);

This will ensure that the limit is never cast directly from a negative value to an unsigned int, and that its value always lives between 0 and MAX_UINT.

As any programmer will tell you, all intense debugging sessions always end with the desperate phrase, “but how did this ever work?”. The same was true for us, and what still bothered me was why we had never seen this error before, since that xapian-bridge code hadn’t been changed for several release cycles now. What had changed this time round was that the part of the codebase that actually handled these queries client-side had recently been ported from JavaScript to C. Grepping through that code base for any sign of the ‘limit’ field, we came across this line:

g_autofree gchar *limit_string = g_strdup_printf ("%d", limit);

The limit field had always had a GObject type of unsigned int, yet here we were treating it as a signed int. Back when this codebase was in JavaScript this line didn’t even exist, because why explicitly convert each property in an object to a string when we can just call JSON.stringify() directly? In C that serialization had to be done manually, and in doing so we mischaracterized an unsigned integer as a signed one. That’s why -1 was even getting sent to the xapian server in the first place – it never happened under Javascript because Javascript isn’t as low-level as C and hence never needed to ask us whether this was a signed integer or not – it ‘just knew’.

Patching this code up was a mere one character change (switch %d to %u ). Last, but not least we fixed the original query to request GLib.MAXUINT32 as its limit. Even though our server now gracefully handled the -1 value, it had always been bad practice to rely upon it. The fact that when I first delved into the code I found that line confusing seemed justification enough to clean it up.

So that was it: three separate bugs, working in tandem to produce this baffling, processor dependent result. I found the entire saga illuminating not only as regards to computer architecture but to the power of paired – or in this case quartet – programming. Each step along the way went faster because someone on our team had domain-specific knowledge that could be shared with the rest of the group. Here’s to more collaborative coding!

Reflections on the political crisis in Brazil: Part 2

Eight months ago I wrote a piece about the current turbulent political situation in Brazil. Since then the drama has hardly let up, and even relative to the political rollercoaster that is 2016 it’s been fascinating. I thought I would record some of it again, for those who may be interested in the trials and tribulations of this Latin powerhouse.

We left off with President Dilma Rousseff, the first female president in Brazil’s history and a member of the once very popular Worker’s Party (PT), facing a key impeachment vote before Congress. A small cabal of senators charged Dilma with violating a rather esoteric and obscure budgeting law written into Brazil’s constitution. As far as I can tell no one understands the law, not even the senators, and no one can explain, concisely and completely, how Dilma broke it, but the general gist of the matter is that she manipulated the government books to conceal or at least understate the true size of the nation’s public debt. The accusation claims she did so deliberately in the run up to the 2014 election in order to win more votes. Dilma of course denies all of this and contends, not without good reason, that the entire impeachment has been orchestrated by her right-wing opponents to remove her party from power – something they’ve been unable to do at the ballot box in over 12 years.

In any case, whatever one thinks about the merits of the charge itself, the actual impeachment proceedings, held on April 17th in the Chamber of Deputies, Brazil’s lower legislative house, turned out to be a rather amusing display of pomp and buffoonery. Brazilian politics is already quite a messy, passionate ordeal, but with the stakes this high, it turned into a circus. Deputies were yelling at each other, waving banners, and chanting the entire night. At times scuffles broke out on the floor as people tried to press their way to the lectern to speak. Much to the embarrassment of many Brazilians, the entire 11-hour session was broadcast live on Brazilian TV and is on YouTube for the whole world to watch. Presiding over the whole affair with calm determination was Eduardo Cunha, President of the Chamber of Deputies, and the man labeled Dilma’s “nemesis” for his role in architecting the impeachment. Cunha called each of the deputies up one by one to declare their vote and provide a brief explanation for why they were voting the way they were. Almost invariably the (usually male) deputy would dedicate his vote in favour of impeachment to some combination of ‘God’, ‘my beloved country’, and ‘my family’. Some felt the need to mention each of their family members by name, with one man, Marcelo Álvaro Antônio, listing each of his children, but, rather embarrassingly, forgetting one son. Realizing to his horror the mistake he had made later in the evening, Marcelo hurried back to the lectern, interrupting the deputy whose turn it was, to state : “Just to correct one thing: I didn’t mention my son, Paulo Henrique: Paulo Henrique this is for you my son!”  Others used their time to rail against the vague menace of ‘corruption’. Hardly anyone referenced the “Fiscal Responsibility Law” (Lei de Responsibilidade Fiscal) which Dilma is alleged to have breached, and none noticed the irony in the fact that 150 members of their own chamber (the majority of whom voted for impeachment) were implicated in crimes far more severe than the one they so sanctimoniously charged Dilma with. Of course, there was righteous indignation – a sentiment to which the Portuguese language seems particularly well-suited – on both sides. Glauber Braga, a socialist deputy from Rio, used his time to call Cunha a “gangster”. Jean Wyllys, a left-wing firebrand and rising star in Brazilian politics, went even further and, in what became one of the most cited speeches of the event, proclaimed the entire proceedings to be a “farce” that was being “conducted by a thief”, “urged on by a traitor”, and “supported by cowards”. Draped in his signature red scarf, Wyllys had to speak louder and louder as his speech went on in order to be heard over the rising din. By the end he was practically screaming:

In the name of the rights of the LGBT population, of the black people and those exterminated [by police] in the favelas, of the culture workers, the homeless, the landless, I vote against the coup! And sleep with that, you bastards!

Jean Wylyss, a socialist deputy from Bahia and the second openly gay member of the Chamber of Deputies, speaks against the impeachment of Dilma Rousseff.
Jean Wyllys, a socialist deputy from Bahia and the second openly gay member of the Chamber of Deputies, speaks against the impeachment of Dilma Rousseff.

Perhaps the most shocking and unforgettable moment of the night came when Jair Bolsonaro, a polarizing, right-wing demagogue, took to the stand and dedicated his vote in favour of impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship. Ustra’s unit was responsible for rounding up and torturing some 500 suspected ‘left-wing terrorists’, including the then young student Dilma Rousseff. In response to Bolsonaro’s ugly move, Jean Wyllys pushed through the crowd and spat on him, which led to fisticuffs breaking out between the two men’s supporters.

Jair Bolsonaro dedicates his vote for the impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship.
Jair Bolsonaro dedicates his vote for the impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship.

In the end, with 367/513 votes, the ayes cleared the ⅔ majority they needed to pass the motion of impeachment. The bill then moved to the senate, who, on May 12th, also passed it, though with much less fanfare. Dilma was now suspended for 6 months while they prepared and conducted the actual trial to determine her guilt. In the meantime, her vice president, Michel Temer, took over. In Brazil vice presidents need not (and indeed often are not) from the same political party as the president, although they do run together on the same ticket. Temer is from the Brazilian Democratic Movement Party (PMDB). A sidenote here: Brazilian political parties are very different from their counterparts in the more ‘developed’ world. Brazilian democracy is very young and, therefore, most parties have not had time to carve out a clear political and ideological territory. As a result, there are literally dozens of active political parties in Brazil – in the Chamber of Deputies alone no fewer than 25 parties are represented – and, unlike in the US or the UK, most ordinary citizens do not describe themselves as being more loyal or more committed to one particular party. No one really has a clear idea of what each party stands for and often even educated, well informed citizens have trouble remembering which politician belongs to which party, simply because it doesn’t seem to make much of a difference in how that politician will vote. The party names also are of no guidance: The “Progressive Party” tends to be pretty conservative and right wing; the Brazilian Women’s Party has exactly one deputy in the Chamber, and he is a man.

Michel Temer assumed the presidency of Brazil after Dilma was impeached. Critics accuse him or helping orchestrate the impeachment for his own personal political gain.
Michel Temer assumed the presidency of Brazil after Dilma was impeached. Critics accuse him or helping orchestrate the impeachment for his own personal political gain.

Supporters of Dilma have long accused Temer of helping orchestrate what they describe as the “illegal coup” against her in order to put himself in power. Suspicions intensified when, just hours before the vote to begin the impeachment trial, Temer committed one of those faux pas we all dread: he accidently sent an audio message to an entire WhatsApp group, when he meant to send it to just one friend. The message appeared to contain parts of a speech which he would give once he assumed the presidency. Given that at that point the country had not yet even opened the case for impeachment proceedings, let alone convicted Dilma, such a prepared speech seemed strangely presumptuous. Temer lost even further credibility when it emerged via Wikileaks that he had, since 2006, been acting as something of an informant for the US government, passing detailed reports and information on the current political situation in Brazil to US Southern Command in Miami. Never forgetting the key role that the Johnson administration had played in the 1964 military coup that had overthrown their first attempt at democracy, many Brazilians regarded these revelations as evidence of treachery and became even more convinced that Dilma’s impeachment was essentially a coup without the tanks.

Despite these setbacks, and with a poll showing that only 2% of Brazilians would vote for him in an election, Temer assumed the presidency. His first move was to establish a new cabinet. What ought to have been a fairly procedural affair blew up into a political firestorm. He appointed a creationist to head the Ministry of Science, and a ‘soybean tycoon who has deforested large tracts of the Amazon rain forest’ for his agriculture minister. What really angered people, however, was that Temer’s cabinet was the first in decades to feature only white men. Coming right after the ousting of what had been a remarkably diverse administration, led by Brazil’s first female president, such a decision seemed like a slap in the face to Dilma’s legacy. The impeachment had already been tinted with sexist overtones – “Tchau querida” (“Goodbye dear”) had become a popular slogan for those wanting Dilma out – and Temer’s cabinet picks seemed only to normalize that. It didn’t help Temer that in the same month Veja, a popular news magazine, published a feature special on his wife, Marcela, a 28-year-old former beauty pageant winner, which they titled ‘Marcela Temer: bela recatada e “do lar” (beautiful, demure, and of the home)’. In it, they praised Marcela for being the type of girl who “wears knee-length dresses”. Those furious at this sexist interpretation of a woman’s place in society were quick to respond with a flurry of memes on social media, posting pictures of strong feminist icons, past and present, captioned (ironically) with the phrase “bela, recatada, e do lar”.

Michel Temer with his wife, Marcela.
Michel Temer with his wife, Marcela.

In terms of actual policy, Temer immediately pursued a program of harsh austerity and neoliberal economics. His administration abolished several ministries, including the Ministry of Women, Racial Equality, and Human Rights, as well as the Ministry of Culture, though the latter he was forced to reinstate 11 days after he dissolved it in response to angry, yet creative protests by a variety of artists and musicians. More troublingly, he pushed through a constitutional amendment that freezes government spending for 20 years. Characterized by UN officials as simply “an attack on the poor”, the PEC55 policy, as it is known, prevents future governments from softening or undoing the austerity, thereby locking in a right-wing economic agenda for two decades and jeopardizing many of the gains made in poverty reduction during the Lula years. The measure fails to even take into account increases necessary to support a rising population, meaning that per capita spending on things like education and healthcare are expected to fall. Despite Temer’s promises that it is the shock therapy Brazil needs to climb out of recession, Brazilians have taken to the streets to protest what Vox dubbed “the harshest austerity program in the world.” The police response – in contrast, some have noted, to how police responded to the Dilma protests – has been swift and unrepentant: firing tear gas and pepper spray at unarmed protesters and blinding at least two journalists with rubber bullets.

A protestor holds a sign saying "Out Temer! Out everyone!". Her shirt says "No to PEC55".
A protestor holds a sign saying “Out Temer! Out everyone!”. Her shirt says “No to PEC55”.

As one of the groups expected to be hardest hit by the spending cuts, students have formed the vanguard in many of these protests. Even before PEC55 kicked in, state governments in Brazil had, of their own volition, been ordering the closure of dozens of schools across the country, in an effort to consolidate resources. Faced with the prospect of having now to attend overcrowded schools further from home, students resisted the closures by occupying hundreds of school buildings across the country, refusing to leave until their demands were met. The national austerity program has only exacerbated the students’ plight, and led to more vociferous protest. In October, sixteen-year-old Ana Julia, one of the students involved in the sit-ins, delivered a speech to the senate in her home state of Paraná. Opening with the words “Who is school for?”, she embarked on a lengthy tirade, defending the legitimacy and necessity of the student occupations and lambasting the legislators for failing to address student needs. She also attacked as “insulting” a recent government initiative escola sem partido, which forbids political discourse in public schools. The senators remained silent and attentive throughout, albeit with looks of mild annoyance at being lectured to by a girl who, for most of them, was young enough to be their granddaughter. When she decried them for having ‘blood on their hands’ – a reference to a student who had recently died during an occupation – they could no longer contain their irritation. Some began to murmur disapproval, and one angrily shouted back “my hands aren’t dirty!”. At this point the president of the senate stepped in, and reprimanded Ana Julia, reminding her sternly “You can’t attack parliamentarians here…here no one has hands stained with blood.” The sixteen year old apologized, but then retorted by quoting the Statute of the Child and Adolescent, which proclaims that “responsibility for our adolescents lies with society, the family, and the state.” At this the public crowd in the gallery erupted in applause and Ana Julia’s video soon went viral. Cries of “Ana Julia me representa” resounded across Brazilian social networks.

Ana Julia defends the student protests before a senate hearing in her home state of Parana.
Ana Julia defends the student protests before a senate hearing in her home state of Parana.

Meanwhile back in the nation’s capital, the ‘Lava Jato’ corruption investigation, which is what had first triggered this political crisis, continued to draw ever more powerful politicians into its proverbial noose. Eduardo Cunha, the man who conducted the impeachment proceedings against Dilma, was arrested and charged with accepting $5 million in bribes from a company bidding on state contracts. As the man most responsible for ousting Dilma, his arrest was greeted with unabashed glee by supporters of her party, especially since he had once vehemently sworn that he would ‘walk to Curitiba [the city from which the investigation was being run]’ if they ever found any real evidence against him. Brazilian meme artists had a field day with this quote and the photo of Cunha being escorted out of his home by federal police.

Eduardo Cunha, the former head of the Chamber of Deputies, was arrested on October 19th.
Eduardo Cunha, the former head of the Chamber of Deputies, was arrested on October 19th.

Next on the chopping block was Renan Calheiros, the canny yet uninspiring president of the federal senate. The Lava Jato team charged him with embezzling government funds and using them to support a daughter he had fathered via an extramarital affair with a journalist. Although his case is yet to reach a conclusion and he denies all charges, a federal judge ordered Calheiros to resign, on the grounds that one cannot be in line for the presidency (as head of the senate he is second in line until Temer appoints his own vice) while being under federal investigation. Calheiros spurned the judge’s order, insisting he would stay right where he was. His refusal sets an alarmingly dangerous precedent – that lawmakers can simply evade and defy the rulings of Brazil’s judiciary, in blatant contravention to the separation of powers principle ingrained in the country’s constitution. The same judge, Justice Marco Aurelio Mello, described Calheiros’ defiance as “inconceivable” and “grotesque”. Calheiros, however, knew he had the tacit support of President Temer, who needs him in the senate to help push through his economic agenda – if Calheiros were to fall, Jorge Viana, a senator from the leftist Worker’s Party and a key ally of the ousted president Dilma, would take over as head of the senate and would no doubt give Temer more resistance to his austerity legislation. After a tense exchange of ever more trenchant rhetoric between the Senate office and the judiciary, the case went to the Supreme Court, who softened Judge Mello’s ruling, allowing Calheiros to remain at his post but still forbidding him from ascending to the presidency in the (not unlikely) event that Temer is forced to resign.

Renan Calheiros, the president of the Brazilian Senate.
Renan Calheiros, the president of the Brazilian Senate.

With Cunha and Calheiros both brought to heel, it became clear firstly that the Lava Jato had no intention of closing shop just because Dilma was gone, and, secondly, that no politician was too powerful to be beyond their reach. Those two facts simultaneously overjoyed the Brazilian populace, and terrified the rest of the political elite. It got to the point where almost every day another politician was charged with some form of fraud or corruption and dragged (sometimes literally kicking and screaming) to a federal prison. But Brazilian politicians are a shrewd and wily bunch, and they were not about to just sit back and wait for the maw of justice to close around them. Something had to be done.

The first was that, just after Temer formally took office, the senate very quietly passed a measure granting executive branches of government much more leeway over budgetary adjustments. The blandly named Law 13.322 allows state and federal administrations to increase spending on a particular budget item, beyond what was originally planned, as long as they took the extra funds from another area of the budget. The Brazilian constitution is in general pretty strict about ensuring that government spending sticks to its planned budget and does not deviate from the amounts defined therein. This law would ease some of those restrictions, and, recognizing that economic priorities can change as events unfold, gives governments much more flexibility to adapt spending to meet changing demand. It all sounds quite sensible, but what is rather peculiar about this measure is that it is this practice – namely, unilaterally borrowing from one part of the budget to add more funds somewhere else without legislative approval – that this same Senate impeached Dilma for just one week prior. Moreover it was Dilma’s administration who originally proposed Law 13.322; had it passed when she was in office, there would have been no grounds for impeachment at all. This is not to excuse the fact that what Dilma did was at the time legally dubious, but it does make one wonder what these senators were thinking when they so piously railed against Dilma’s financial imprudence and corruption, if they were going to make what she did legal just one week after. The answer of course, is that these politicians are now desperately trying, ex post facto, to patch the gaping hole in their argument, which is that these accounting tricks, while not completely above bar, had been used, and are still being used, all around Brazil at all levels of government. To be consistent, Dilma’s opponents would have to also throw out all the state governors who did the exact same thing. A lot of those governors are friends or political allies of theirs, so they don’t want to do that. The only solution, therefore, is to be inconsistent, and hurriedly try to shield their comrades from suffering the same fate they just leveled against Dilma.

Having patched the hole they had pushed Dilma through, Brazil’s congressmen then moved to stymie the Lava Jato investigation. While the country was distracted mourning the death of an entire football team in an airplane crash, Brazil’s lower house frantically rewrote an anti-corruption bill to introduce penalties against judges said to have abused their power. They didn’t mention him by name, but the obvious target of the measure was Sergio Moro, the regional judge who is spearheading the Lava Jato investigations. Critics of the bill warn it would “erode the independence of the judiciary.” The chamber also edited the law to maintain certain statute of limitations which will ensure that many of their corrupt members will avoid jail time. The end result would be to make Lava Jato toothless. In response, Brazilians have taken to streets yet again in protest, many of them donning banners proclaiming support for Sergio Moro.

Judge Sergio Moro, the man spearheading the Lava Jato investigation, is seen as a national hero by many Brazilians. Critics say he is overstepping his authority.
Judge Sergio Moro, the man spearheading the Lava Jato investigation, is seen as a national hero by many Brazilians. Critics say he is overstepping his authority.

And that’s where we are now. Brazilian politics continues to lurch from crisis to crisis, with an overall mood that is at once both depressing and terrifying. There are a troublingly growing number of calls for a return to military rule, as well as serious threats of secession from southern states in the country. Having managed to keep its image together for the Summer Olympics, Brazil has hit turbulence again, and is still plagued by economic stagnation. Cynicism, especially about politics, is as Brazilian as football and cachaça, and this year has only reinforced that. I hope that 2017 gives the people of this wondrous country reason to buck that tradition.