Quick thought on hashstore log file classes

Inspired by a recent conversation with @Pentium100, started thinking about how log files should be split into two classes. I’m focusing only on pieces that do not have explicit expiration date at upload.

The working assumption here is that data uploaded comes from one of two cases: short-lived and long-lived. We do not know upfront if a piece will be short-lived or long-lived. Outside of compaction process, each log file produced will contain both short-lived and long-lived pieces. When the short-lived pieces are deleted, these log files would end up with a non-trivial amount of data deleted, leading to compaction. Then, the pieces that managed to survive long enough are mixed into some new log files.

Now, the fact that these pieces survived should be a useful signal: they may actually belong to the long-lived class! As such, maybe instead of putting them into log files that also accept new traffic (with an unknown mixture of short-lived and long-lived pieces), they should be compacted into a new log file made just to collect compaction output. This way we would, in some sense, distill the long-lived pieces into a log file that will likely not need compaction for far more time, and hence reducing I/O.

This process would mirror the garbage collection algorithms in various memory-managed languages. These algorithms usually have a concept of gen1 and gen2 storage. This model of garbage collection is an established, long-validated pattern, so why not apply it to our log files as well?

And there’s another potentially useful optimization that follows: the “fresh uploads”/gen1 log files should be smaller than the “distilled”/gen2 log files, again, to reduce I/O. If you have 1000 log files each with 10 MB data, there’s higher chance that you will find a couple of log files where almost all content was short-lived, than if you had 10 log files with 1 GB of data.

Any volunteer to vibe code it? :grin:

Don’t logs naturally become filled with more long-lived data over time? The short-lived stuff gets deleted and compacted… the long-lived survives to get poured in one efficient sequential write into the next log. That should also lead to older logs not getting compacted as often?

I don’t think we have to do anything. Just sit on our hands, and hope Storj lives…

The node knows when the piece has a TTL, and pack them to the logs with the similar TTL.
But I think you mean when the piece doesn’t have a TTL.
Also, I believe that @Roxor is correct and this happen automatically over time.

Not really. What you and @Roxor are speaking about is the log files themselves, which stay as long as the compaction procedure lets them. I am speaking about qualities of specific pieces in these files. A log file does not change piece composition after being written, their basic property is that once written and finalized, they are never changed again.

Yes, I understand that. What I mean, that they will be compacted, sure, until they will contain only long-living pieces, after that they should become static and will not be rewritten anymore.

I think it’s easy to confirm - we can take a look on how old these logs

Yeah the compact-one-log-file-at-a-time-by-itself is a simple design but as you say does not exploit the unbalanced lifetime of the segments.

Edit: There is some connections to theoretical computer science (e.g. bin packing) for what the good achievable and optimal algorithms would do, depending on your modelling assumptions

https://dl.acm.org/doi/10.1145/3491045

These are often not really practical but something to learn from.

Also this older paper we ought to consider so we don’t reinvent the wheel: https://web.stanford.edu/~ouster/cgi-bin/papers/lfs.pdf

Would you like to do it yourself? We have a lot of context in the code already so a coding AI should have easy game here.

All you need to do is tell compact to compact by age. It selects a bunch of log files based on the amount of dead space in them. It will naturally start with the log file that has the highest amount of dead space in it. Change that order to start with the oldest data. Just the age of the first or if possible the last piece in that log file. Not the age of the log file on disk since that gets updated on every compact itteration. The age of the piece doesn’t change.

With these few lines of code you mission is already completed. Compact itself will just copy the pieces out of these log files into new log files. So 5 log files with 20% dead space will be written into 4 log files. With the correct order you now get 3 log files with old pieces that will most likely remain on disk for some time.

Its not perfect but easy enough to try it out. Few lines of code. Ideally with a feature flag. And we can measure before and after this change how the pieces are distributed. There are improved versions of this. We could make it so that compact reads all the piece ages in the selected log files and puts them into the perfect order. That would require a lot more free space to run. So we would need some safety checks and maybe fall back on the previous solution if there is not enough free space for the luxury solution.

:thinking: maybe we should start with the measurement. We are both making assumptions that might not be correct. Depending on the lifecycle of a piece it could be that right now most of the log files already have old pieces in them and are uniform. If so even a more luxury solution would not help.

In any case this is all you are asking for. We don’t need to introduce a fancy job for this. By the time compact is running the hashtable is passiv and will not receive any uploads. So no need to worry about that part. Plus compact is going to get in touch with the older pieces after the younger pieces already got deleted. It would be ideal to utilize that. After confirming that our assumptions are correct.

Not with the crunch I have now at work, but later… maybe?

I don’t think so? This proposal is about which log files the compacted data go to, not which log files are compacted. So, we’d need to find a way to designate some log files as target for fresh traffic, some for compacted data. Could be as simple as odd/even ID split… I guess?

Yeah, if we had more detailed logs about piece longevity, we could check if the thesis that pieces are either short-lived or long-lived is true.

There is no need for that. Compact does that already. There are 2 hashtables per satellite. One is active and gets fresh uploads. The other is passiv and gets compacted. Every now and than they switch roles. So the moment compact runs it is garanteed that there is no fresh traffic for that hashtable.

There is an extra debug tool for that. You can print out a lot of details for each log file.

And the moment tables switch roles, a log file used for compacted data that was not filled starts receiving new traffic.

Survivorship bias.

@littleskunk suggested to start with the measurement, so I measured my nodes.

Setup: 264 nodes, one operator (same /24), all satellites, hashstore with memtbl, v1.164.2.
A small read-only tool opens the current hash table of every store (s0/s1) and lists the log files.
Per piece it uses Created and Length. Dead space = log file size − live − trash.
3,172 stores read in about 8 minutes.

1. Dead space that compaction never touches

About 65 TiB (11 %) of the log files is dead, almost all in non-TTL logs that are 50–90 % alive.
On US1 that is about 68,000 logs at 50–75 % alive and about 145,000 logs at 75–90 % alive. With alive-fraction 0.25 these are practically never rewritten. So @Alexey is right that old logs become static, but they stay static with 10–50 % dead space each.
The 14 TiB of trash on Spiridon sits in logs that are over 90 % alive and will add to this once it expires.

2. Age mixing depends on where the data came from

  • Migrated data (US1, EU1, AP1): pieces 150–400 days apart in age inside the same 1 GiB log.
  • Data uploaded directly to hashstore (Spiridon and the newest satellite): 0–6 days apart.

So for new data @Roxor and @Alexey are right: logs are age-sorted by themselves.
For migrated data @Toyoo is right: one log mixes pieces up to a year apart.
The likely reason is the migration from piecestore: it walks the piecestore directories in sorted order, and those are named after the first two characters of the random piece ID. So pieces went into the logs in piece ID order, which has nothing to do with their age. New uploads are written in arrival order, so a log fills with pieces from the same hours or days.
The walk order is from the code, that it explains all of the mixing is my reading of the numbers.

3. Where compacted data goes, and how long pieces live

@Toyoo, on your point about where compacted data goes: in the current code, compaction writes the surviving records into the same pool of open log files that uploads use. For every record it takes any open log that is not full and has the same TTL class, and only skips the logs that are being rewritten. So today compaction output and fresh uploads do share log files, and a log filled by compaction keeps taking uploads afterwards.

On piece longevity: the tool now also counts the live data per upload week. I will run it weekly on these 264 nodes and can post how much of each week’s uploads is still alive after 1, 2, 4 and 8 weeks. That should show whether young pieces die much faster than old ones.

4. What this suggests

Compacting by age mainly helps the migrated data. It could be cheap: read the records in offset order as today, and write them out sorted by Created. The bigger lever for the 65 TiB is freeing dead space without copying the 50–90 % that is alive.
I have been testing two changes to compaction on a test PC with a 24 TB Exos (XFS) and a test node on Spiridon.

5. Punching holes instead of rewriting

5. Punching holes instead of rewriting

Compaction punches the ranges of expired pieces out of log files that are not rewritten (fallocate(PUNCH_HOLE)), after the new hash table is committed. Live pieces stay where they are, offsets do not change, and the space goes back to the filesystem right away.

  • 100 log files with 37 GB dead: holes of 64 KiB and up freed 96 % of it in 12 s, without reading or writing any live data. A rewrite of the same logs copies 70 GB, about 22 minutes on that disk.
  • 20M realistic pieces (median 40 kB) on the HDD: 460 GiB freed over three simulated days without copying. Simulated downloads during compaction: median 63 ms with punching against 469 ms with the normal rewrite.
  • Most dead space sits in small gaps: holes of 64 KiB and up catch 96 %, 1 MiB and up only 55 %.
  • XFS writes the changed metadata back about 30 s later in one burst (about 2,000 small writes for 3,400 holes), which delayed downloads to 0.5–2 s for a few seconds. Punching at 25 holes per second removed that completely.
  • Holes leave the free space in small pieces, so when the disk gets nearly full, holes count as dead space again and those logs are rewritten, which merges the holes. xfs_fsr does not help here: it reports punched logs as “already fully defragmented”.
  • Punched pieces read as zeros and fail the piece hash check, so rebuilding the table from the logs does not bring them back. An unpatched node can read punched logs.
  • Only pieces that expire after punching is turned on are punched. The dead space that is already there needs a one-time pass, which I have not built yet.
6. Buffering the rewrite in memory

6. Buffering the rewrite in memory

My nodes share a server with more than 3 TB of RAM, so I tried using memory when logs do get rewritten: read the live records in large sequential reads (64 MiB, reading along small dead gaps), keep them in memory until the machine has 10 % of its memory left, then write everything out. Each node checks the available memory before every 64 MiB, so many nodes can do this at once.

  • About 10 % faster than the record-by-record copy on the HDD. With the hash table on an NVMe it was 23 % faster.
  • Buffer size does not matter beyond 64 MiB: 64 MiB, 1 GiB and “all free memory” gave the same speed. The disk is the limit, not the memory: the copy already runs close to its sequential speed.
  • Reading along dead gaps is a trade-off. Gaps under 1 MiB: 10 % faster, but downloads during compaction at 360 ms median. Gaps under 256 KiB: the same speed as today, but downloads at 85 ms against 503 ms.
7. Two smaller findings

7. Two smaller findings

  • On XFS, hashstore.store.prealloc-alignment (default 64 MiB) marks log files as preallocated, and XFS then never trims the speculative preallocation after their end.
    A full 1 GiB log took 3 GiB on a nearly empty disk. With prealloc-alignment: 0 my test node has 0.04 % overhead, and compaction was not slower.
  • I also tried making compaction share blocks with reflink on XFS. It wrote 4x less, but was about twice as slow on a HDD because live pieces get split up, so I dropped it.

Caveats: one operator, all nodes in one /24, so the data is similar across nodes. Ages are whole days. The benchmarks are on one disk model.

Th3Van.dk

With the solution I outlined it would be the log file that has the newest pieces anyway.

How that? You are claiming that by sorting the pieces by age you get a benefit on the next compact run. Instead of 10 log files with 10% dead space each you can make it 2 log files with 50% dead space. Less work for compact. Thats great but you can put that theory to a test without having to implement it. Run the debug tool and verify if you assumption is correct.

Which is the exact opposite of what the idea is about.

Not sure what you are responding to. Any tool that statistically analyses data from log files will be affected by the survivorship bias, making them overrepresent long-lived pieces. The analysis will not be accurate.

I guess we are done here. I am trying to help and see no reason to defend myself. Take it or leave it.

Negative. If you run the analyses now you get an accurate snapshot with all the new log files that have been uploaded to you yesterday. Track these log fiels down. According to your assumption you would expect a different dead space ratio over time compared to older log files. To some extend I would expect that new uploads might get deleted within a week or so but they are already located in the same log file anyway. After a week that log file might get compacted and the remaining pieces can age together in a new log file. Now the question is how is the filespan of the remaining pieces that survive the first compact run. Is there still a higher chance that the customer deletes them? Or is there a more or less uniform risk that a piece might get deleted after 3 month vs after 1 year. If the risk is the same you can’t gain anything by sorting them in different log files. You would still end up with 10% dead space spread over all log files the same way it is now.

Yeah, that was supposed to be a quick thought, but without shared vocabulary it necessarily turns into a long-winded discussion. Let’s drop it indeed.

Is the idea being discussed… that when a compaction is triggered… it ONLY runs if enough logs are compacted that at least one new full “old log” can be created? So it tries not to intermingle old data into the same pool of open log files that uploads use?

So it’s trying to make completely-full-hopefully-never-touched-again old logs? Like a 55%-full log and 60%-full log don’t just get randomly mixed in to that “pool of open log files that uploads use” - instead the system makes a 100%-full old-log… and only pours the leftover 15% into the general pool?

I’m trying to wrap my head around this.

I did what I suggested earlier and measured it instead of arguing about it. :slightly_smiling_face:

Method: I picked one store (us1, s0) on one of my nodes and took 150 of its 3037 non-TTL log files, spread evenly by log id (= roughly evenly over time). That’s 161 GB in total. A small read-only script walks the 64-byte record footers of each log backwards, the same way fsck does. It then checks every record against the hashtbl: still referenced → alive (trash counts as alive), not referenced → dead. The created field of each record gives the piece age.

Dead share by piece age:

piece age all logs “upload” logs “mixed” logs
0–30 days 15.5 % 15.1 % (too little data)
30–90 days 18.7 % 21.6 % 5.8 %
90–180 days 14.8 % 19.0 % 11.1 %
180–365 days 12.9 % 20.1 % 11.4 %
1–2 years 13.2 % (too little data) 13.6 %

“Upload” = 80 % of the pieces in the log are within 14 days of each other (filled by direct uploads), 68 logs, 18.5 % dead overall. “Mixed” = everything else (migration/compaction output), 82 logs, 12.2 % dead overall.

So young pieces die somewhat more often, but not by much. The mixed logs full of 1–2 year old pieces still carry ~13 % dead data. Moving fresh uploads into separate gen1 logs would not clean that up. If anything, the old buckets are underestimated, because dead old pieces had more time to get compacted away already.

Where the dead bytes are, per log:

dead share of the log logs share of all dead bytes
0–10 % 56 8 %
10–20 % 41 28 %
20–30 % 36 38 %
30–40 % 16 24 %
≥ 40 % 1 2 %

90 % of the dead bytes sit in logs that are still 60–90 % alive. With the default alive-fraction: 0.25 and probability-power: 2, the chance of such a log being picked per compaction run is ((0.25/0.75) * (1-alive)/alive)^2, i.e. between 0.7 % and 5 %. These logs are effectively never rewritten. Across all my nodes DataReclaimable adds up to about 15 % of the log size, so it’s not a small amount.

My takeaway: the problem is less that ages are mixed and more where the selection threshold sits. Separating log classes would not change much here. I have just started a test with hashstore.compaction.alive-fraction: 0.5 on two nodes (two other nodes as control). That raises the per-run probability for 60–90 % alive logs to roughly 6–44 %. The price is more rewrite IO, about 3 GB written per 1 GB reclaimed. I’ll report back in a week or two with how fast DataReclaimable goes down and what it does to disk utilization and success rates.

Caveat: one store on one node. Happy to see numbers from other nodes, the script is below. It is read-only and runs at idle IO priority (nice -n19 ionice -c3 python3 logage.py <store dir> 150 out.csv), about 15 s per log on my HDDs.

logage.py
#!/usr/bin/env python3
# Read-only analysis of a hashstore store: for a sample of log files, walk the record footers
# backwards and classify each record as alive / trash / dead by comparing with the hashtbl.
# usage: logage.py <store dir (…/<sat>/s0)> <nsample> <out.csv>
import os, sys, glob, struct, time, collections

store, nsample, out = sys.argv[1], int(sys.argv[2]), sys.argv[3]
REC = 64

def parse(b):
    return dict(
        offset=int.from_bytes(b[32:38], "little"),
        log=int.from_bytes(b[38:46], "little"),
        length=int.from_bytes(b[46:50], "little"),
        created=int.from_bytes(b[50:53], "little") & 0x7FFFFF,
        expires=int.from_bytes(b[53:56], "little"),
    )

logs = {}
for p in glob.glob(os.path.join(store, "??", "log-*")):
    _, lid, ttl = os.path.basename(p).split("-")
    if int(ttl, 16) == 0:
        logs[int(lid, 16)] = p
ids = sorted(logs)
sample = set(ids[::max(1, len(ids) // nsample)][:nsample])

tbl = sorted(glob.glob(os.path.join(store, "meta", "hashtbl-*")))[-1]
table = collections.defaultdict(dict)
with open(tbl, "rb") as fh:
    fh.seek(4096)
    while chunk := fh.read(64 << 20):
        chunk = chunk[: len(chunk) // REC * REC]
        for i, (lid,) in enumerate(struct.iter_unpack("<38xQ18x", chunk)):
            if lid in sample:
                r = parse(chunk[i * REC:(i + 1) * REC])
                if r["length"]:
                    table[lid][r["offset"]] = r["expires"]

with open(out, "w") as w:
    w.write("log,log_bytes,state,created,length\n")
    for lid in sorted(sample):
        try:
            fd = os.open(logs[lid], os.O_RDONLY)
        except FileNotFoundError:
            continue
        size = os.fstat(fd).st_size
        alive = table.get(lid, {})
        pos, bad = size - REC, 0
        while pos >= 0 and bad <= (1 << 20):
            r = parse(os.pread(fd, REC, pos))
            if r["log"] != lid or r["offset"] + r["length"] != pos:
                pos, bad = pos - 1, bad + 1
                continue
            exp = alive.get(r["offset"])
            state = "dead" if exp is None else ("trash" if exp & 1 else "alive")
            w.write(f"{lid},{size},{state},{r['created']},{r['length']}\n")
            pos = r["offset"] - REC
        os.close(fd)

So, I still think your analysis is biased because of the survivorship bias and the existing compaction selection mechanisms. To perform the analysis correctly, you would have to know the lifetime of each piece, even the ones that were compacted away already. I’d do this analysis myself before posting the idea if I had the right dataset for it—but I do not have per-piece deletion timestamp.

I’ll probably instrument my nodes to collect this data somehow.

As I said, let’s drop it for now.

I have included my script. Feel free to adjust that to your needs. The script looks into the existing dead space before compacting. You are also free to implement what ever improvement idea you might have. I already shared what I have changed on a few of my nodes and will report the results in a few days.

Does this mean that you have preserved the log files that would normally be deleted a year ago?