mail_deduplicate.deduplicate module

The deduplication pipeline: group mails by hash, settle each set, keep score.

The Deduplicate orchestrator drives the whole run. Both of its expensive steps, hashing and selection, can fan out across worker processes: the module-level _-prefixed functions are the halves that run inside a worker.

mail_deduplicate.deduplicate.step_progressbar(**kwargs)[source]

A progress bar for one step of the run, drawn on a terminal only.

Off a terminal, Click prints a bar’s label once instead of the bar. Each step already opens on a heading saying the same thing, so in a log, a pipe or a capture the label is a bare line repeating it. Hiding the bar there drops that line, and leaves a terminal the bar --progress asks for.

The bar draws on sys.stderr, as click_extra.progressbar() makes it, unless file names another stream: that is the stream checked.

Parameters:

kwargs (Any) – what click_extra.progressbar() takes.

Return type:

ProgressBar[Any]

mail_deduplicate.deduplicate.path_order(mail)[source]

Sort key ranking mails by path, then by ID among the mails of one file.

A set of mails iterates in an order that changes from one run to the next. Sorted by this key, the same mails come out in the same order on every run.

Return type:

tuple[str, str]

class mail_deduplicate.deduplicate.Stat(*values)[source]

Bases: Enum

All tracked statistics.

The member’s name carries the category as its MAIL_/SET_ prefix, and its value the description shown in the final report.

MAIL_FOUND = 'Total number of mails encountered from all mail sources.'
MAIL_REJECTED = 'Number of mails rejected individually because they could not be read.'
MAIL_UNHASHED = 'Number of mails with too few of the hashed headers to compute a hash. They joined no duplicate set, and were kept in the final selection like unique mails.'
MAIL_FAILED = 'Number of mails set aside, and left untouched, because hashing them failed on an unexpected error. The bug report after this table tells how to report it.'
MAIL_RETAINED = 'Number of valid mails parsed and retained for deduplication.'
MAIL_HASHES = 'Number of unique hashes.'
MAIL_UNIQUE = 'Number of unique mails (which were automatically added to selection).'
MAIL_DUPLICATES = 'Number of duplicate mails (sum of mails in all duplicate sets with at least 2 mails).'
MAIL_SKIPPED = 'Number of mails ignored in the selection step because the whole set they belong to was skipped.'
MAIL_DISCARDED = 'Number of mails discarded from the final selection.'
MAIL_SELECTED = 'Number of mails kept in the final selection on which the action will be performed.'
MAIL_COPIED = 'Number of mails copied from their original mailbox to another.'
MAIL_MOVED = 'Number of mails moved from their original mailbox to another.'
MAIL_DELETED = 'Number of mails deleted from their mailbox in-place.'
MAIL_HARDLINKED = 'Number of mails replaced in-place by a hardlink to the copy kept in their duplicate set.'
SET_TOTAL = 'Total number of duplicate sets.'
SET_SINGLE = 'Total number of sets containing only a single mail with no applicable strategy. They were automatically kept in the final selection.'
SET_SKIPPED_SIZE = 'Number of sets skipped from the selection process because they were too dissimilar in size.'
SET_SKIPPED_CONTENT = 'Number of sets skipped from the selection process because they were too dissimilar in content.'
SET_SKIPPED_TIMESTAMP = 'Number of sets skipped from the selection process because a timestamp could not be derived for some of their mails.'
SET_SKIPPED_STRATEGY = 'Number of sets skipped from the selection process because the strategy could not be applied.'
SET_SKIPPED_ERROR = 'Number of sets skipped from the selection process because reading or comparing their mails failed on an error.'
SET_DEDUPLICATED = 'Number of valid sets on which the selection strategy was successfully applied.'
property description: str

The description of the statistic, shown in the final report.

property category: str

Whether the statistic counts mails or sets, read off the member’s name.

exception mail_deduplicate.deduplicate.SizeDiffAboveThreshold[source]

Bases: Exception

Difference in mail size is greater than threshold.

exception mail_deduplicate.deduplicate.ContentDiffAboveThreshold[source]

Bases: Exception

Difference in mail content is greater than threshold.

exception mail_deduplicate.deduplicate.MissingTimestamps[source]

Bases: Exception

Some mails of a set have no timestamp for time-based strategies to compare.

Happens for mails without a parseable Date header, when the timestamp is sourced from it.

class mail_deduplicate.deduplicate.BodyHasher(*values)[source]

Bases: StrEnum

Enumeration of available body hashing methods.

Each value interprets the body one step further than the one before it. skip leaves the body out. raw hashes its bytes as the box holds them, with line endings reduced to LF. decoded undoes the transfer encodings and decodes the text, so copies that differ in their encoding alone hash the same. normalized also strips all whitespace first.

SKIP = 'skip'
RAW = 'raw'
DECODED = 'decoded'
NORMALIZED = 'normalized'
property function: Callable[[DedupMailMixin], str]

The callable producing this member’s body hash for one mail.

class mail_deduplicate.deduplicate.DuplicateSet(hash_key, mail_set, conf)[source]

Bases: object

A set of mails sharing the same hash.

Implements all the safety checks required before we can apply any selection strategy.

Load-up the duplicate set of mail and freeze pool.

Once loaded-up, the pool of parsed mails is considered frozen. This allows aggressive caching of lazy instance attributes depending on the pool content. Only replace_pool() changes the pool, and it drops these attributes.

hash_key: str
selection: set[DedupMailMixin]

Mails selected after application of selection strategy.

unique: set[DedupMailMixin]

The subset of the selection no strategy ever ruled on.

A mail alone in its set has no copy to be compared to, so it is kept without any criterion picking it over another. Held apart from the rest of the selection so a destructive action can leave it alone. See: https://github.com/kdeldycke/mail-deduplicate/issues/1053

discard: set[DedupMailMixin]

Mails discarded after application of selection strategy.

conf

Configuration shared from the main deduplication process.

pool: frozenset[DedupMailMixin]

Pool referencing all duplicated mails and their attributes.

stats: Counter[Stat]

Set metrics. Unset statistics naturally read as zero.

replace_pool(pool)[source]

Replace the pool, and drop every property cached on the previous one.

Each cached property of the set derives from its pool. One computed before the change, like the biggest size the size threshold compares, would still describe the mails set aside.

Return type:

None

property size: int[source]

Returns the number of mails in the duplicate set.

property timestamps: tuple[float, ...][source]

Returns the timestamps of all mails in the set.

Raises MissingTimestamps if a timestamp could not be derived for some mails, naming them so users can locate and fix them. See: https://github.com/kdeldycke/mail-deduplicate/issues/132

property newest_timestamp: float[source]

Returns the newest timestamp among all mails in the set.

property oldest_timestamp: float[source]

Returns the oldest timestamp among all mails in the set.

property biggest_size: int[source]

Returns the biggest size among all mails in the set.

property smallest_size: int[source]

Returns the smallest size among all mails in the set.

property paths: dict[DedupMailMixin, str][source]

Returns the file path of each mail in the set.

A mail derives its path from its box at each access, and a path-based strategy reads the paths of the set once per --regexp expression. The set is dropped once settled, and its paths with it.

check_differences()[source]

Checks the mails of the set against each other for size and content.

Their differences must stay within the limits the thresholds set.

Instead of rejecting the whole set on the first offending pair, the mails involved in the most offending pairs are greedily set aside until every remaining pair passes the thresholds. This keeps a single outlier from preventing the deduplication of the true copies sharing its set. See: https://github.com/kdeldycke/mail-deduplicate/issues/851

Returns the mails to set aside, empty if the whole pool already passes.

Raises SizeDiffAboveThreshold or ContentDiffAboveThreshold if fewer than 2 mails would remain, in which case there is no coherent core of duplicates and the whole set is to be skipped, as before.

Return type:

set[DedupMailMixin]

diff(mail_a, mail_b)[source]

Return the difference between two mails’ decoded body, in bytes.

The unified diff of the two bodies is measured in UTF-8, the unit of --content-threshold and of size.

Todo

Rewrite the diff algorithm to not rely on naive unified diff result parsing.

Return type:

int

pretty_diff(mail_a, mail_b)[source]

Returns a verbose unified diff between two mails’ decoded body.

The body lines carry no line ending, so no diff line gets one either: they are joined with one instead.

Each line is styled by the active theme, the way git diff colors its own: a removed line as an error, an added one as a success, the hunk range as a range, and the two file headers as structure. The log handler strips the styling wherever color is off.

Return type:

str

skip_set(reason, stat)[source]

Mark the entire set as skipped.

Return type:

None

select()[source]

Settle which mails of the set are selected and which are discarded.

Run preliminary checks, then apply the strategies to the pool of mails, each in turn until one produces a proper selection.

The process results in two subsets of mails: the selected and the discarded.

Return type:

None

select_or_skip(failures)[source]

Run select(), and skip the whole set if it raises an error.

Returns the error, ready for the bug report, or None when the selection went through or the error needs no report. See skip_on_error().

Return type:

Failure | None

skip_on_error(expt, pool, failures)[source]

Skip the whole set after an error, as a set failing a safeguard is skipped.

Whatever the interrupted selection recorded is dropped, and the full pool is accounted for, so none of its mails is acted upon. An OSError means a mail could not be read again, which needs no bug report. Any other error is captured for the report and returned.

Return type:

Failure | None

class mail_deduplicate.deduplicate.HashedMail(mail_hash, timestamp, mail_size, rejection, failure=None, unhashed=None)[source]

Bases: NamedTuple

What a hashing worker sends back for one mail.

Deliberately nothing but scalars, and the strings of a Failure for a mail that hit an unexpected error: the parsed message stays in the worker and dies with the task, so a few dozen bytes cross the process boundary instead of the whole mail. Which mail an answer belongs to is not carried either, as fan_out() hands every answer back alongside the task it came from. The parent rebuilds the same dehydrated stub it would have produced itself, exactly as it does for a mail restored from the cache.

Create new instance of HashedMail(mail_hash, timestamp, mail_size, rejection, failure, unhashed)

mail_hash: str | None

Alias for field number 0

timestamp: float | None

Alias for field number 1

mail_size: int | None

Alias for field number 2

rejection: str | None

Alias for field number 3

failure: Failure | None

Alias for field number 4

unhashed: str | None

Alias for field number 5

class mail_deduplicate.deduplicate.HashOutcome(mail, mail_hash, rejection=None, failure=None, unhashed=None)[source]

Bases: NamedTuple

What the hashing step makes of one mail, ready to be merged into the run.

At most one of mail_hash, rejection, failure and unhashed is set: a mail is retained, rejected for a reason that needs no bug report, set aside after an error that does, or kept without a hash, as it has too few headers to compute one.

Create new instance of HashOutcome(mail, mail_hash, rejection, failure, unhashed)

mail: DedupMailMixin

Alias for field number 0

mail_hash: str | None

Alias for field number 1

rejection: str | None

Alias for field number 2

failure: Failure | None

Alias for field number 3

unhashed: str | None

Alias for field number 4

mail_deduplicate.deduplicate.unreadable(expt)[source]

Words the rejection of a mail whose file the system refused to read.

Return type:

str

class mail_deduplicate.deduplicate.MailMeta(source_path, mail_id, path, timestamp, mail_size)[source]

Bases: NamedTuple

All a worker needs to rebuild one mail of a duplicate set from its own file.

Create new instance of MailMeta(source_path, mail_id, path, timestamp, mail_size)

source_path: str

Alias for field number 0

mail_id: str

Alias for field number 1

path: str

Alias for field number 2

timestamp: float | None

Alias for field number 3

mail_size: int | None

Alias for field number 4

class mail_deduplicate.deduplicate.SelectedSet(selected, unique, discarded, stats, records, failure=None)[source]

Bases: NamedTuple

What a selection worker sends back for one duplicate set.

Mails are named rather than returned: the parent already holds them, and shipping them back would mean pickling every message it worked so hard not to keep.

Create new instance of SelectedSet(selected, unique, discarded, stats, records, failure)

selected: tuple[tuple[str, str], ...]

Alias for field number 0

unique: tuple[tuple[str, str], ...]

Alias for field number 1

discarded: tuple[tuple[str, str], ...]

Alias for field number 2

stats: dict[Stat, int]

Alias for field number 3

records: tuple[tuple[int, str], ...]

Alias for field number 4

failure: Failure | None

Alias for field number 5

class mail_deduplicate.deduplicate.Deduplicate(conf)[source]

Bases: object

Load mails, search for duplicates, apply the strategies and perform the action.

Similar messages sharing the same hash are grouped together in a DuplicateSet.

CHUNK_SIZE: int = 200

Mails handed to a hashing worker in one go.

Each queue round-trip costs far more than hashing a single mail, so tasks travel in chunks. Large enough to make that cost disappear, small enough that the last worker to finish does not hold up the others.

SET_CHUNK_SIZE: int = 32

Duplicate sets handed to a selection worker in one go.

Smaller than the hashing chunk because a set is several mails’ worth of work, so fewer of them already amortize the same round-trip.

sources: dict[str, Mailbox]

Index of mail sources by their full, normalized path. So we can refer to them in Mail instances. Also have the nice side effect of natural deduplication of sources themselves.

mails: dict[str, list[DedupMailMixin]]

All mails grouped by hashes.

Grouped in lists rather than sets: mails carry no value equality, so a set only ever deduplicated by object identity, which the single pass over each box already rules out. A one-element list also costs 64 bytes where a set costs 216, and most hashes group a single mail.

selection: set[DedupMailMixin]

Mails selected after application of selection strategy.

unique: set[DedupMailMixin]

The subset of the selection no strategy ever ruled on.

It holds the mails that have no duplicate, which each duplicate set contributes here: see DuplicateSet.unique. It also holds the mails with too few headers to be hashed, which join no duplicate set at all.

discard: set[DedupMailMixin]

Mails discarded after application of selection strategy.

Maps each discarded mail to the selected mail it can be hardlinked to.

Left empty unless the configured action consumes it: see track_link_targets.

conf

Configuration shared across the deduplication process.

Whether each discarded mail has to be paired with a selected one.

Only the hardlinking action needs that pairing, and it costs one dictionary entry per discarded mail, so it is settled once here and only recorded when something reads it.

stats: Counter[Stat]

Deduplication statistics. Unset statistics naturally read as zero.

loaded: int

Number of mails the sources held when they were opened.

Only sizes the progress bar of the hashing step. Stat.MAIL_FOUND is counted from the listing that step reads instead, as another program can deliver or remove mails between the two steps. A maildir takes no lock that would stop it.

failures

The errors no rule explains, each of which put a mail or a duplicate set aside.

step

What the run is doing, named by the bug report of an error that stops it.

source_formats: Counter[str]

Number of boxes opened in each format, for the bug report.

Counted as the boxes open, since closing them empties sources.

cache: HashCache | None

Cross-run cache of mail hashes, when the user opted in with --cache and the database could be opened.

restore_cached(box, mail_id, entry)[source]

Rebuild a hashed mail from its cache entry, without opening its file.

Produces the same dehydrated stub the hashing step would have left behind, with the scalars the later steps rely on already memoized. Anything else those steps need is re-read from the box on demand, as for any other mail.

Return type:

HashOutcome

blank_stub(box, mail_id)[source]

An empty mail carrying only its identity, ready to be filled in.

Stands in for a mail this process never parsed, because its content came from the cache or from a worker that has already thrown it away.

Return type:

DedupMailMixin

parallel_boxes()[source]

The sources whose mails a worker process could hash on its own.

Only folder-based boxes qualify. Their mails each own a file, which a worker opens by path, sharing nothing. Mails of a file-based box are byte ranges of one file that a single handle seeks through, so handing them out would mean several processes seeking the same descriptor.

Returns an empty list unless every source qualifies, so a run is either wholly parallel or wholly sequential rather than silently half of each.

Return type:

list[Mailbox]

property jobs: int

Worker processes the --jobs option resolved to, read off the context.

worker_pool(jobs, initializer, initargs, verb, doing)[source]

Hand out a pool of worker processes prepared by the initializer.

The pool shuts down however the block it wraps ends.

Yields None instead when the pool cannot be started, which is the case in some frozen or sandboxed environments: the initializer is then run right here, so the worker functions find the state they expect, and the caller degrades to sequential calls instead of dying.

Return type:

Generator[ProcessPoolExecutor | None, None, None]

fan_out(pool, worker, tasks, window, chunksize)[source]

Yields each task back alongside its worker’s answer.

Tasks pair what the parent keeps with the payload its worker receives, and are handed out a window at a time rather than all at once: map() consumes whatever it is given immediately, so passing the whole corpus would hold a task per mail, undoing the flat memory the rest of the run maintains. The window is wide enough that every worker always has chunks queued behind it.

With or without a pool, answers come back in submission order, so whatever the caller aggregates comes out identical to a sequential run at any number of workers.

Return type:

Iterator[tuple]

uncached(boxes, absorb, progress)[source]

Yields the identity of every mail the cache cannot answer for.

A mail the cache can restore is absorbed here and never even opened, which is the whole point of keeping the cache. Lazy, and driven from the main process alone: neither box objects nor the cache are safe for concurrent access.

Return type:

Iterator[tuple[Mailbox, str]]

hash_in_parallel(jobs, absorb, progress)[source]

Hash every uncached mail across a pool of worker processes.

Threads cannot do this job: what hashing spends itself on is Python-level work that the interpreter lock serializes, so fanning it out across threads only adds contention. Processes sidestep the lock, and the mail never has to travel: a worker opens its own file and sends back a hash and two scalars.

Return type:

None

adopt_hashed(box, mail_id, result)[source]

Turn a worker’s answer back into the mail stub this process works with.

Return type:

HashOutcome

add_source(source_path)[source]

Registers a source of mails, validates and opens it.

Duplicate sources of mails are not allowed, as when we perform the action, we use the path as a unique key to tie back a mail from its source.

A source that cannot be opened or listed raises MailSourceError: the error comes from the source or its format, which the user can fix.

A run that deletes or moves mails also refuses a source in a profile that Thunderbird has open, as Thunderbird checks none of the locks taken here. A copy or a rehearsal of the same run goes on. The same run on a maildir with no new, like a Thunderbird folder, warns to repair that folder after the run: Thunderbird does not check those folders against their summaries.

A run out of open files gets a message of its own, as every mbox, babyl and mmdf box holds its file open until the end of the run. The message says how to raise the limit: the run never changes the limits of the system itself.

A source in which no mail is found gets a warning.

Return type:

None

hash_all()[source]

Read the mails of all sources, compute their hashes and group them by hash.

Displays a progress bar as the operation might be slow.

Each mail is dehydrated as soon as it is hashed, so whatever the size of the corpus, only a lightweight stub of every mail is retained. See: https://github.com/kdeldycke/mail-deduplicate/issues/761

Hashing fans out across worker processes when --jobs resolves above 1 and every source is a folder-based box; otherwise mails stream through this process one at a time, which is also the lowest-memory path. Box listing and the hash cache always stay in this process, as neither is safe for concurrent access, so the speedup is largest where the hashing itself is the cost, with --hash-body decoded/normalized.

Return type:

None

build_sets()[source]

Build the selected and discarded sets from each duplicate set.

The selection is settled one duplicate set at a time, to keep the memory footprint low and make the log easier to read.

Return type:

None

settle(hash_key, mail_set)[source]

Settle one set in this process, and merge its verdict into the run.

The set goes through the thresholds and the strategies.

Return type:

None

log_set_heading(hash_key, mail_count)[source]

Announce a duplicate set, at a level reflecting whether it holds copies.

Styling the heading is not free, and most sets hold a single mail and so report at debug level, where the result is thrown away: only pay for it when it is actually logged.

Return type:

None

release(mail_set)[source]

Drop the content the thresholds and strategies pulled back from the boxes.

Iterating on the original set covers skipped sets and set-aside mails too, which land in neither selection nor discard. See: https://github.com/kdeldycke/mail-deduplicate/issues/362

Return type:

None

Pair every discarded mail of a set with a selected mail of that same set.

Hardlinking a discarded mail only makes sense against a copy that survives the very set both were found in, and that pairing is the one thing the flat selection and discard sets no longer say once every set has been settled.

A strategy is free to keep several mails, so the target is the one with the lowest path: a run then links to the same copy however the sets came back, which matters when the selection is spread over a pool of processes.

Iterables are only walked once the run is known to need them, so a call from a non-hardlinking run costs nothing beyond the arguments themselves.

Return type:

None

select_in_parallel(jobs, progress)[source]

Apply the selection to every duplicate set across a pool of processes.

Duplicate sets share nothing with one another, so a set is the natural unit of work. Only sets holding copies are handed out: a set of one is settled without reading anything, and would cost more to ship than to decide.

Return type:

None

describe(mail)[source]

Everything a worker needs to rebuild a mail, and nothing more.

Return type:

MailMeta

adopt_selection(hash_key, mail_set, result)[source]

Merge a worker’s verdict on one set back into this process.

The heading and the worker’s own messages are said here, in that order, so the log reads as it would have from a sequential run however the sets were spread out.

Return type:

None

close_all(flush=True)[source]

Close all open boxes, and the hash cache if one was opened.

With flush off, the pending changes of the boxes stay unwritten: see release_box(). Closed boxes and cache are dropped, so calling this again does nothing.

A single-file box with pending changes then gets a warning. The trail of the action step already listed its mails as deleted or moved, while its file still holds every one of them.

Return type:

None

report()[source]

Returns a text report of user-friendly statistics and metrics.

Return type:

str

report_failures()[source]

Log the bug report of the mails and sets the run set aside.

Returns whether there were any, so the run can end with an error code.

Return type:

bool

assert_stats(first, operator, second)[source]

Render failed stats assertions in plain English.

Statistics that do not add up are a bug: the run logs a bug report and exits with code 115.

Return type:

None

check_stats()[source]

Perform some high-level consistency checks on metrics.

Helps users reports tricky edge-cases.