Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions .agent/rules/compile-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,29 @@ rule below has already been at least one of the two.

## The five rules the end-to-end tests assert

<!-- agent-tripwire: Preprocess with line markers suppressed -->
<!-- agent-tripwire: Preprocess KEEPING line markers; the key keeps their line numbers and drops their paths -->

`pace-kv` and `pace-cc` are both installed. Three things the launcher's
cache key depends on, each of which has already caused a silent hit-rate
collapse or a mis-serve and is now covered by regression tests:

- **Preprocessing must suppress line markers** (`/EP` on MSVC, `-E -P` on GNU).
A `# 1 "/abs/path.cpp"` marker embeds the checkout path in the hashed text.
On MSVC that is `/EP` **alone**: `/EP` and `/P` are alternatives, not modifiers
— `/EP` preprocesses to stdout, `/P` to a `<base>.i` file, and MSVC documents
the pair as "to the file, without `#line`". Passing both left the launcher
hashing an empty stdout, so a Windows key carried nothing from the source and
an edited file was answered with the object built from the previous revision.
That is a wrong build rather than a cold cache, and direct mode hid it, since
its manifest hashes the source's own bytes — hence the e2e case that edits a
source with `PACE_NO_DIRECT=1` and requires a MISS.
- **Preprocessing KEEPS line markers (`/E` on MSVC, `-E` on GNU), and the key keeps
their line numbers while dropping their paths** (`KeyedPreprocessedText`). A
`# 1 "/abs/path.cpp"` marker embeds the checkout path, which is why the probe used to
suppress markers outright (`/EP`, `-E -P`) -- and that threw the LINE STRUCTURE away
with the path: `-P` collapses blank and comment lines, so a comment inserted above a
function left the hashed text byte-identical while `std::source_location`,
`__builtin_LINE` and every `-g` line table moved. Measured end to end: the edited file
got a HIT whose function reported line 2 where the source said 5 (`objkey-v10` fixed it).
The path is safe to drop because nothing a key could see depends on it: `__FILE__` is
already expanded in the text, and a name recorded after preprocessing is root binding's
and the prefix maps' to answer.
- On MSVC never `/P` beside it: `/P` preprocesses to a `<base>.i` file rather than
stdout, and `/EP /P` left the launcher hashing an empty stdout, so a Windows key
carried nothing from the source and an edited file was answered with the object
built from the previous revision. Direct mode hid it, since its manifest hashes the
source's own bytes — hence the e2e case that edits a source with
`PACE_NO_DIRECT=1` and requires a MISS.
- **`/` introduces an option only on Windows.** On POSIX it starts an absolute
path, and treating it as an option leaves absolute paths unrelativized.
- **Only machine-independent dependency paths may be hashed.** The dependency set
Expand Down Expand Up @@ -344,8 +351,8 @@ same on both — the same defect with no MSVC anywhere near it.

<!-- agent-tripwire: Only machine-independent dependency paths are hashed, and a path is classified by what it *resolves to*, never by its spelling -->

- **A key determines two artefacts, so it must be a function of both.** Preprocessing
suppresses line markers (`-E -P`, `/EP`) so a checkout path never reaches the key —
- **A key determines two artefacts, so it must be a function of both.** The keyed text
carries no checkout path (each line marker is reduced to its line number) —
which is what makes a key portable, and equally what made it *invariant under a header
move*. Move a header without changing a byte of it and the token stream is identical:
the object is still correct and was served, while the depfile, which is nothing but
Expand Down Expand Up @@ -702,7 +709,9 @@ same on both — the same defect with no MSVC anywhere near it.

**The channel follows the FLAG, not the driver.** Both drivers put the notes on
stdout when compiling and move them to stderr under `/EP`, where stdout carries the
preprocessed text and a note on it would corrupt that text. The three sites said
preprocessed text and a note on it would corrupt that text. The probe has since moved
to `/E` (`objkey-v9`), whose channel nobody here has MEASURED; it decides nothing,
because the probe reads notes from both streams and splits stdout unconditionally. The three sites said
"`cl` on stderr"; #700 and the #821 review said "`cl` on stdout"; each was half
right and neither had the rule. That is what makes a claim restated in three places
dangerous — none of the three was placed to notice the question had a second
Expand Down
2 changes: 1 addition & 1 deletion AGENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ the only place it is written down.

**[`.agent/rules/compile-cache.md`](.agent/rules/compile-cache.md)** — what the
launcher's cache key is made of. Before `apps/pace-cc/`, `CompileCache/`.
- Preprocess with line markers suppressed — `/EP` **alone** on MSVC, never `/EP /P`.
- Preprocess KEEPING line markers; the key keeps their line numbers and drops their paths — `/E`, never `/P`.
- `/` introduces an option only on a Windows layout; on POSIX it starts a path.
- Only machine-independent dependency paths are hashed, and a path is classified
by what it *resolves to*, never by its spelling. A CPM cache is a ROOT (`<DEPROOT>`, `PACE_DEPS_DIR`).
Expand Down
6 changes: 6 additions & 0 deletions docs/tools/pace-cc.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ preprocess-only run moves the notes (clang-cl puts them on stderr under `/EP`,
so that they do not corrupt the preprocessed stdout), so the probe splits stdout
unconditionally and reads notes from both streams rather than guessing.

The probe keeps its line markers (`-E`, `/E`) and the key keeps their line numbers
while dropping their paths. Suppressing the markers (`-E -P`, `/EP`) collapsed blank
and comment lines, so a comment inserted above a function kept the key while
`std::source_location`, `__builtin_LINE` and the `-g` line tables moved, and the
edited file was served the object built before the edit.

Version-suffixed (`g++-14`, `clang-18`) and `.exe` forms are recognised. Any
other `argv[0]` is treated as unknown and passed straight through uncached.

Expand Down
80 changes: 79 additions & 1 deletion src/apps/pace-cc/CacheKey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <Pace/CompileCache/PathCanon.hpp>

#include <algorithm>
#include <cstddef>
#include <format>
#include <optional>
#include <span>
Expand Down Expand Up @@ -214,6 +215,74 @@ std::optional<std::string> UnkeyableArgument(std::span<std::string const> args,
return std::nullopt;
}

namespace
{
/// The marker a line opens with, reduced to what the key keeps, or nothing when the
/// line is not a marker.
/// @param line One line without its terminator.
/// @return The line as written up to its line number, then what followed the quoted
/// path, or nullopt.
[[nodiscard]] std::optional<std::string> ReducedMarker(std::string_view line)
{
auto rest = line;
if (!rest.starts_with('#'))
return std::nullopt;
rest.remove_prefix(1);
auto const skipBlanks = [&rest] {
while (!rest.empty() && (rest.front() == ' ' || rest.front() == '\t'))
rest.remove_prefix(1);
};
skipBlanks();
if (rest.starts_with("line") && rest.size() > 4 && (rest[4] == ' ' || rest[4] == '\t'))
{
rest.remove_prefix(4);
skipBlanks();
}
auto const digits = rest.substr(0, rest.find_first_not_of("0123456789"));
if (digits.empty())
return std::nullopt;
rest.remove_prefix(digits.size());
auto const throughLineNumber = line.substr(0, line.size() - rest.size());
skipBlanks();
if (!rest.starts_with('"'))
return std::nullopt;
// The path is a C string literal: a backslash escapes the next byte, so `\"` does not
// end it, and MSVC doubles every separator (`c:\\src\\a.cpp`).
auto at = std::size_t { 1 };
while (at < rest.size() && rest[at] != '"')
at += rest[at] == '\\' ? 2 : 1;
if (at >= rest.size())
return std::nullopt;
rest.remove_prefix(at + 1);
return std::format("{}{}", throughLineNumber, rest);
}
} // namespace

std::string KeyedPreprocessedText(std::string_view text)
{
std::string out;
out.reserve(text.size());
while (!text.empty())
{
auto const end = text.find('\n');
auto const length = end == std::string_view::npos ? text.size() : end + 1;
auto const line = text.substr(0, length);
// The terminator (`\n`, or `\r\n`) is kept as written, so only the marker's path moves.
// `\r\n` ends with `\n` too, so the two tests sum to 2 for it, 1 for a bare `\n`, 0 for none.
auto const terminatorSize = std::size_t { line.ends_with('\n') } + std::size_t { line.ends_with("\r\n") };
auto const body = line.substr(0, line.size() - terminatorSize);
if (auto const reduced = ReducedMarker(body))
{
out.append(*reduced);
out.append(line.substr(body.size()));
}
else
out.append(line);
text.remove_prefix(length);
}
return out;
}

std::string CacheCompilerId(std::string_view banner, std::string_view targetTriple)
{
if (targetTriple.empty())
Expand Down Expand Up @@ -351,7 +420,16 @@ std::string ComputeKey(KeyInputs const& inputs)
// rather than merely old and nothing in a value says which ones are -- v6's argument. This
// construction is unchanged and the golden vector moved for the tag alone; `manifest-v10`
// moves with it, in the lock-step ComputeManifestKey records.
KeyDigest digest { "objkey-v9" };
//
// v10 is the line structure. `preprocessed` was `-E -P` / `/EP` output, which collapses
// blank and comment lines, so a comment inserted above a function kept the key while
// `source_location`, `__builtin_LINE` and the `-g` line tables moved: the edited file was
// served the object from before the edit (measured end to end: a HIT whose function
// reported line 2 where the source said 5). It is now `KeyedPreprocessedText` over output
// that keeps its markers. Every key moves, so the tag moves with them rather than leaving
// a v9 cache whose entries no current key can reach to be explained later. `manifest-v12`
// moves with it, in the lock-step ComputeManifestKey records.
KeyDigest digest { "objkey-v10" };
digest.Field(inputs.compilerId);
digest.Field(inputs.preprocessed);
for (auto const& arg: inputs.relativizedArgs)
Expand Down
19 changes: 19 additions & 0 deletions src/apps/pace-cc/CacheKey.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ struct KeyInputs
std::string_view buildTree,
PathCanon::PathTransform const& resolve = {});

/// The preprocessed text the key hashes: the probe's output with every line marker's PATH
/// removed and its line number and flags kept.
///
/// The probe keeps its markers (`-E`, `/E`) because they carry the line structure: without
/// them a comment inserted above a function left the text byte-identical while
/// `std::source_location`, `__builtin_LINE` and every `-g` line table moved, so the edited
/// file was served the object built before the edit. The marker's path is what made it
/// unportable -- it is the checkout's absolute path -- and nothing in the object depends on
/// it that a key could see: `__FILE__` is already expanded in the text, and a file name the
/// compiler records after preprocessing (`source_location::file_name`, debug records) is
/// root binding's and the prefix maps' to answer.
///
/// Both spellings are recognised: GNU's `# <line> "<path>" <flags>` and MSVC's
/// `#line <line> "<path>"`. A line that is not a marker of either shape -- a `#pragma`, an
/// assembler comment -- is kept verbatim, as is every other byte.
/// @param text The probe's stdout.
/// @return The text with each marker reduced to its line number and flags.
[[nodiscard]] std::string KeyedPreprocessedText(std::string_view text);

/// `RelativizeArgs` over a whole layout, its dependency root included: a path under
/// `layout.dependencyRoot` becomes a `<DEPROOT>` token, so an include directory into a
/// per-user dependency cache stops keeping the user's home in every key.
Expand Down
58 changes: 57 additions & 1 deletion src/apps/pace-cc/CacheKey_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,7 @@ TEST_CASE("ComputeKey's value is pinned, so changing the construction is deliber
// to disagree about what was hashed, and the retirement check would go vacuous
// in the one edit it exists to catch.
auto const key = ComputeKey(inputs);
CHECK(key == "ccb841c6012c541ddf44ebaefe48132b");
CHECK(key == "0fc3b62f1f1ddc380c8517b715d4f018");

// What the vector alone cannot say: that the tag has not been put BACK. See
// Generation -- reverting the tag and re-pasting the vector is one edit
Expand All @@ -449,6 +449,9 @@ TEST_CASE("ComputeKey's value is pinned, so changing the construction is deliber
{ .key = "objkey-v7", .digest = "7323057f60d9ffaca969b16ef293ceaa" },
// The v8 -> v9 bump (a clang worker's dropped macro map) changed nothing but the tag.
{ .key = "objkey-v8", .digest = "e86dc84efc6cb5de598620cc334f4ee7" },
// The v9 -> v10 bump (the line structure) moved what `preprocessed` holds, not how it is
// folded, so this is the outgoing vector.
{ .key = "objkey-v9", .digest = "ccb841c6012c541ddf44ebaefe48132b" },
});
RequireNoRetiredDigest<std::string_view>(key, Retired);
}
Expand Down Expand Up @@ -814,6 +817,59 @@ TEST_CASE("A prefix-map flag's root is relativized, so two checkouts still share
CHECK(keyFor(RootA, {}) == keyFor(RootB, {}));
}

TEST_CASE("The keyed text keeps every marker's line and drops its path")
{
// `-E -P` collapsed blank and comment lines, so a comment inserted above a function left
// the key unchanged while `source_location`, `__builtin_LINE` and the `-g` line tables
// moved -- measured on g++ and clang++, one key and two objects. The probe keeps its
// markers now and the key keeps their line numbers; the paths, which differ per checkout,
// go.
SECTION("GNU markers, flags kept, every other byte untouched")
{
std::string const in = "# 0 \"/home/a/src/t.cpp\"\n"
"# 1 \"/usr/include/c++/16/vector\" 1 3\n"
"#pragma GCC diagnostic push\n"
"int f() { return 1; }\n"
"# 12 \"/home/a/src/t.cpp\" 2\n";
CHECK(KeyedPreprocessedText(in)
== "# 0\n"
"# 1 1 3\n"
"#pragma GCC diagnostic push\n"
"int f() { return 1; }\n"
"# 12 2\n");
}
SECTION("MSVC #line, doubled separators and CRLF")
{
std::string const in = "#line 1 \"c:\\\\src\\\\t.cpp\"\r\nint g();\r\n#line 40 \"c:\\\\src\\\\t.cpp\"\r\n";
CHECK(KeyedPreprocessedText(in) == "#line 1\r\nint g();\r\n#line 40\r\n");
}
SECTION("an escaped quote does not end the path")
{
CHECK(KeyedPreprocessedText("# 3 \"/w/odd\\\"name.h\" 1\n") == "# 3 1\n");
}
SECTION("what is not a marker stays verbatim")
{
for (std::string_view const line: { "#pragma once\n",
"# not a marker\n",
"#line x \"a\"\n",
"# 7 unquoted\n",
"# 7 \"unterminated\n",
"#define X 1\n",
" # 5 \"/a\"\n" })
{
INFO(line);
CHECK(KeyedPreprocessedText(line) == line);
}
}

// The property, stated on its own: two checkouts' markers agree, and a moved line does not.
auto const at = [](std::string_view root, int line) {
return KeyedPreprocessedText(std::format("# {} \"{}/src/t.cpp\"\nint h();\n", line, root));
};
CHECK(at("/home/alice/work/fc", 5) == at("/srv/bob/deeper/fc", 5));
CHECK(at("/home/alice/work/fc", 5) != at("/home/alice/work/fc", 8));
}

TEST_CASE("A source prefix map's root is relativized, and the build tree's place under it is keyed")
{
// Catch2's own CMake passes `-ffile-prefix-map=<checkout>/=` on every compile, so its
Expand Down
32 changes: 16 additions & 16 deletions src/apps/pace-cc/CmdLine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,23 @@ namespace
// the launcher cares about. A new driver is a new row here plus a name
// pattern below; the parsing logic itself never grows a branch.

// Both spellings must suppress line markers. `#line` / `# 1 "file"` markers
// embed the ABSOLUTE source path, which would make the preprocessed text —
// and therefore the cache key — differ between two checkouts of the same
// content at different paths, defeating cross-machine sharing entirely.
// MSVC: /EP writes to stdout without #line. GNU: -P suppresses markers.
// Both spellings KEEP line markers, and the key strips only the paths out of them
// (`KeyedPreprocessedText`). A `#line` / `# 1 "file"` marker embeds the ABSOLUTE source
// path, which would make the key differ between two checkouts of the same content; but
// suppressing the markers outright (`-E -P`, `/EP`) also threw away the LINE STRUCTURE.
// `-P` collapses blank and comment lines, so a comment inserted above a function left the
// hashed text byte-identical while `std::source_location`, `__builtin_LINE` and every
// `-g` line table moved -- measured on g++ and clang++: one key, two different objects,
// and the edited file was served the old object. The marker's line number is what keeps
// those lines in the key.
//
// `/EP` ALONE, and the absence of `/P` here is the whole point. The two are
// not additive: `/EP` preprocesses to stdout, `/P` preprocesses to a FILE, and
// MSVC documents the pair as "write the file without #line directives". So
// passing both sent the preprocessed text to `<base>.i` and left the launcher
// hashing an essentially empty stdout — a key with no content in it at all,
// under which an edited source re-fetches the object built from the OLD text.
// Direct mode hides it (its manifest hashes the source's bytes), so it showed
// up only with PACE_NO_DIRECT=1, and it dropped a stray `.i` in the
// working directory on every probe besides.
constexpr std::array<std::string_view, 1> MsvcPreprocess { "/EP" };
constexpr std::array<std::string_view, 2> GnuPreprocess { "-E", "-P" };
// `/E` and never `/P` beside it. `/P` preprocesses to a FILE rather than stdout, and the
// pair `/EP /P` sent the text to `<base>.i` and left the launcher hashing an essentially
// empty stdout -- a key with no content in it at all, under which an edited source
// re-fetched the object built from the OLD text. Direct mode hid it (its manifest hashes
// the source's bytes), so it showed up only with PACE_NO_DIRECT=1.
constexpr std::array<std::string_view, 1> MsvcPreprocess { "/E" };
constexpr std::array<std::string_view, 1> GnuPreprocess { "-E" };

/// Preprocess flags for text that is going to be COMPILED elsewhere, which
/// keep the `#line` markers the key's own probe suppresses.
Expand Down
Loading
Loading