Evan bio photo

Evan

Noticing Birds.

Email LinkedIn Public Key Github

Slides      Feedback

So you’ve got no timestamps on a table. Someone forgot to add them, or the column exists, but is mostly null.

Is it possible to recover the missing data? Yes

Should you do it? Probably not.

Each row in Postgres has a hidden metadata column that reveals the ordinality of when it was written. If you learn the secret cord, you too can possibly recover this missing data.

tl;dr

tl;dr The xmin column on every row is monotonically increasing (most of the time). Using xmin from rows with known times, you can impute the missing times.

Before we can get into the results, we need to cover a lot of ground on how postgresql works internally. First, some history.

Pessimistic Locking

office

Let’s say we’re in the 1920s, and you’re a clerk. You want to check on some accounts of ships that have been at sea longer than expected and update a slate of ships with their status.

You go to the document shelf and find the book of ships is missing. Your colleague Bobbertson is updating the book, with the latest info from the telegraph, and you won’t be able to read the updates until he’s done.

This is a form of pessimistic locking, where writes (updates and deletes) are blocking reads. Modern databases allow users to write and read the same rows, but how does that work?

Optimistic Locking, but First; What is a Tuple?

doctor

When ever you read about databases, authors fluidly switch between the word row and tuple. The postgresql glosery defines the tuple as a synonym for row. History, the row is from the 1960s relational Cod model, but like groovy and far out, people don’t keep using 1960s words for fun.

For what I can tell, row/tupple is a mater of persepective. When talking about a row, it’s typically from how the application developer would see it. A much more (opisite of abstract) point of view. A tuple is how postgresql views the row internally. When you go to the doctor, you might say “tummy ache”, but the doctor writes in their notes “patient presents with abdominable discomfort”. This point of view opens more lower leval abstrations which a “tummy ache” obsures.

Talking about tuples allows us to talk more about tuple headers and system columns, and how postgresql impliments MVCC.

So what is MVCC?

Postgres uses a form of optimistic locking called Multiversion Concurrency Control. At the core of this technique is the transaction ID. Postgres assigns a transaction ID to each call. When that call writes or updates rows, that transaction id is assigned to a hidden column called xmin.

When querying, Postgres checks the session’s transaction ID and only returns the tuples with an xmin lower than that session ID. This concept is called visibility.

So how do we find missing timestamps?

Let’s say we have the following data:

-------------------------------------
| table_name |  xmin   | created_at |
-------------------------------------
| events     | ...34   | breakfast  |
| users      | ...35   | ?????      |
| events     | ...36   | lunch      |
-------------------------------------

Given that we know the times at transaction IDs 34 and 36, we can reasonably assume that xmin 35 was written at brunch. This is the happy case, and it can work well in many cases.

Updates, trouble ahead.

When updating a row, Postgres is inserting a new tuple with the updater’s transaction ID, and marking the old tuple as dead, for the vaccum to clean up later. If a read started mid-update, that read won’t see the new tuple until after the update is finished.

We now know the process that transaction IDs go up with queries, and are associated with when the tuple was inserted, which makes it ambiguous if it’s when a row was updated, or initially created.

So, on update, you get an insert and a delete. This splits the logical row into two physical tuples. This allows for the reader to finish their query, and the writer to update rows without interrupting readers.

The big issue for us is that the xmin is not when a row was written, but when the tuple was written, and thus is when the most recent update happened. This means we need to figure out if a given row was updated, or written initially.

Unhappy Cases

Thus begins our descent into madness explaining the pitfalls of using xmin to backfill dates.

For this blog post, we’re going to look at a synthetic dataset of three tables. We have events, users, and buildings. You can get the synthetic dataset generating code here: synthetic_data.rb.

There are many issues with real-world datasets. The best way to see them is by graphing your data.

For those of you following along at home, the first step you’re going to want to do is pull out all the timestamp data you do have and make a graph. The export process has two steps. First is a query against the public_schema table to generate the query to export the data we need.

SELECT 'SELECT table_name, id, xmin, created_at FROM ' || table_name || ' UNION ALL ' AS query
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE';
Screen shot investor's report
This is the ideal case, you've got a solid line showing inserts, and some snow of updates. This is easy to solve.

To build a model to backfill dates, we’ll need the table names, their primary keys, the xmin of each row, and the available timestamps. You’ll almost certainly need to modify this query to take into account how your schema uses different ways to store data. Any timestamps stored in an integer column will need to be coerced into a timestamptz column.

Here, I’m using R, but you can use your graphing program of choice to make these graphs.

Updates

Give that an update also updates the xmin column, and that xmin is when the tuple was written and is more akin to an updated at column. We need to separate the rows which have been updated from the rows that have never been updated.

The simplest technique I’ve found is to perform this divination in each table individually, and this only works on sortable primary keys. Generally, primary keys are monotonically increasing, and are written in order. This is only true when restoring from a dump, and not when backfilling from a .sql file.

We can step over each row, and compare the xmin of the row to the subsequent xmin. If the row’s xmin is greater, then the row has probably been updated. Here is the R version.

df %>% filter(tbl == 'events')  %>%  mutate(was_updated = xmin >= lead(xmin))

There are two issues with this technique. First, an upsert can insert and update rows, and it’s impossible to separate the two. Second, rows updated soon after insertion look like inserts.

But, we want to recover when a row was written, and inaccuracy is inherent to the process. If you’re reading this post, then something has already gone wrong for you.

Imports and Backfills for the cliffs of Insanity

cliff

There are two types of updates that can make this task harder, imports and backfills.

Let’s say you have multiple data stores. Some things are kept in MongoDB, and others are in DynamoDB. You decide you want to do joins, and so you export the data and move it into Postgres. Generally speaking, the rows imported will have the same transaction ID, regardless of the date. This shows up in a graph as a wall or cliff. You can’t trust that cliff, so you’ll need to exclude it from your sample. The big issue with imports is that you often can’t reliably date rows from before the import.

The other way to make a cliff is mass updates or backfilling data. Say you have a large users table, and you want to rotate all the user’s passwords, or you want to add a login count. This will result in all the rows being updated, which again, creates a cliff. You can either remove the cliffs or work between the cliffs. This isn’t as bad as large imports can be.

Seaonality.

The synthetic dataset is simple. I created events at random. This is rare in real life, as most processes have seasonality and trend. Transactions at an ice cream parlor have a positive trend, and strong seasonality. People love ice cream on hot days, and tend to enjoy it less in the winter. People are coming around to ice cream being a healthy snack, and the trend for ice cream sales is increasing. You’ll need to figure out if your data has seasonality. More advanced imputation techniques theoretically have more accurate results.

Norm Violating Assumptions?

What is Creation?

Most developers use a created_at column to store when the record was inserted. Other developers past might have a different idea of what creation entails. They might think it’s when another system received the data, or when the event happened. Maybe even when a conversion started. For a chemical spill, it might take weeks before the spill is noticed, days for it to be reported, and hours for it to be ingested. Which date did the developers use? You might have access to the code, or that code might be gone, rewritten into a new language, and not tracked on git. You can see this with Lambda, which is not necessarily tracked by git. For conversions, it could be the initial time of the event, say when a user first came to the site, not when they finally signed up. I suspect this is rare, having only heard about this sort of issue.

Timezone Offsets

An issue I’ve caused, and uncovered is timezone offsets. A developer might directly connect to production, and start pushing data into production locally. There might be a miss configuration, and so you end up with a constant offset.

The easiest way to find this sort of issue is knowing the default timezones of past developers. Using git, you can use this command to pull up their emails, sorted by count of commits.

git log -100 --pretty=format:%ae | sort | uniq -c | sort

This should give you a hint as to why there might be a discontinuity between IDs and timestamps.

Actually backfilling dates.

So you’ve isolated your dataset to between the cliffs of insanity, adjusted for timezones, anomalous timestamps, and separated out the updates from plausible inserts. You’ve determined there is no seasonality. How do we actually backfill the data?

What is interpolation, vs imputation.

Imputation is finding a missing value in a time series, like timestamps and xmin.

Interpolation is a technique for doing so.

These steps are specific to R, and using the tsimpute library. You could do this in other ways, I’d also recommend a language like python with numpy. I’d recommend against this in postgresql. You’ll need to convert the timestamps to seconds from epoch, so that math can easier find the times between missing dates. You’ll sort the dataset you have by xmin, leaving the null timestamps interspersed. tsImpute handles the work of imputing the missing values. This is for the updates. To do the inserts is the second step. You’ll run this code over just the rows you marked as inserts. If you have a significant number of updates, you’ll have less accuracy on when the rows were initially inserted. To measure accuracy, you’ll want to split about 20% of the rows with known data off as a validation set. This will allow you to determine how accurate the imputation was. The main metric here is mean absolute error, calculated as such:

The main metric here is mean absolute error, calculated as such: \(\sum_{i=1}^{D}\|x_i-y_i\|\) It can be helpful to look at distribution of absolute errors, to figure out if there would be any wildly out of range errors, which is possible with estimating the data.

Once you’ve verified the data is pleasing, you can export the data frame as a csv, and do a bulk update. This will destroy the xmins you used, and you won’t be able to rerun this analysis.

Explaining backfilling dates for 23,000 years

Should you start backfilling these dates, you create problems that you most likely won’t experience, and you won’t be able to advise on. This problem will be experienced by someone with no idea who you are.

How do you mark that the backfilled dates are not originals? There might come a time when someone notices a date that’s off, maybe a junior analyst who’s trying to figure out why their analysis has some weird artifact, or a user reports a date being way off.

You could make a new column. But after a while, people will forget what it’s for, and possibly drop it. Or just never use it.

The oral history of an organization is limited by the person with the longest tenure, which in many organizations is fairly short. This means that after a couple of years, most of the people who remember this project will be gone.

It’s easy to have an engineering culture with an up-to-date wiki in zirp times, but you might wind up with a “Global Capitol Partners” laying off most of the engineering, and leaving a slowly dwindling cloister of monks to maintain the old abby.

Documentation lasts longer than memories but suffers from decay. Wiki systems get moved, from GitHub to confluence, to another system. Metadata is lost, the author, the commentary in the margins, dates of creation, and hierarchy in a tree of documents. Documents can become like stone artifacts, out of place and separated from the culture that created them.

Embedding Dates into Monumental Architecture.

Hoover Dam Star Chart

At its full capacity, the Hoover Dam, located on the Colorado River, stores a sufficient amount of water to satisfy New York City’s water needs for 26 years. Unless a congressional decision mandates its removal, the dam is expected to endure for the next 60,000 years. To aid future societies, including post-apocalyptic urban explorers, extraterrestrial beings, or mysterious entities like the Nephilim, the architect Oskar J.W. Hansen thoughtfully incorporated a star map when the dam was completed. By examining this diagram, anyone who stumbles upon it in the future would have the means to precisely determine the day the Hoover Dam was constructed.

I posit that structured data in a relational database has the longest survivability for most companies. The best way to embed explainability into the backfill is to embed explainability is to encode “high salience numbers” into the timestamps.

High Salience Numbers

A high salience number depends on the culture of the people maintaining the people maintaining the system. Numbers come and go out of style, and what’s relevant to you, might not be relevant to the next generation. Limiting high salience numbers is the need to fit things into timestamps. A number like 69 for example doesn’t fit into a base sixty-time system.

The goal here is to break the future person out of their tools, to look at the rows one by one, and examine the data specifically. We can use the a marker into the factional second portion of the timestamp.

So the rows should look like this.

11:11
22:22

Then they fire up psql, and see the same repeating number on all the backfilled dates:

11:11:11.111
22:22:22.222

This allows almost 12 hours of coverage for timestamps, which should be sufficient for most purposes.

By seeing the repeating digits, it should prompt them to see it as an artifact of process and to try to google that number, or to look in the remains of the wiki system to see if that number brings up anything.

A better number for your context should be picked.

Conclusion

Using xmin to determine dates is possible, but a perilous route to recover missing data. To do so in bulk creates future chaos which can leave people lost and unknowing. Creating timestamps that can be searched for in a wiki system can allow future people to find out what happened.

When you discover an issue like this, where the application developers cannot be trusted to track row creation, the first step should be modifying the schema to have postgresql track creation for you.

ALTER TABLE events ALTER COLUMN created_at SET DEFAULT CLOCK_TIMESTAMP()

This migration is relatively fast, and saves you from needing to track down every process writing to the database updating a long departed developers custom ORM.

If you have a production database, I’d love a sample, please reach out at eunoia.github@gmail.com