mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 04:54:00 +01:00
fix(server): stamp built commit into service.version (#11748)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server emits OpenTelemetry spans so operators can trace agent work > - Each span needs a service version that identifies the code that produced it > - The current service version comes from a static environment value and can become stale after a rebuild > - This pull request records the built commit and resolves the service version from the build stamp, runtime Git, the environment, or an unknown fallback > - The benefit is trace data that identifies the correct built commit during development and deployment ## Linked Issues or Issue Description **What happened?** The server used a static `OTEL_SERVICE_VERSION` value for every OpenTelemetry span. Rebuilds could produce traces with an old commit value. **Expected behavior** The server should report the built commit when a build stamp exists. It should use runtime Git, the environment value, or `unknown` as fallback. **Steps to reproduce** 1. Set `OTEL_SERVICE_VERSION` to an old commit value. 2. Build the server at a different commit. 3. Start the server and inspect the OpenTelemetry service version. 4. Confirm that the built commit takes precedence over the old environment value. ## What Changed - Add a build script that writes the short Git commit to `dist/build-info.json`. - Resolve `service.version` from the build stamp, runtime Git, the environment, or `unknown`. - Log the resolved service version once during server startup. - Add tests for the resolution order and safe behavior without Git. - Document the resolution order in `doc/observability.md`. ## Verification - `pnpm --filter @paperclipai/server build` - `npx vitest run server/src/__tests__/service-version.test.ts` - `pnpm --filter @paperclipai/server typecheck` - Confirm that the build stamp contains the short commit. - Confirm that the stamp wins over the environment value. - Confirm that a build without Git exits successfully without a stamp. ## Risks The server now prefers the built commit over `OTEL_SERVICE_VERSION`. A build without Git uses the existing environment value or `unknown`. The change needs no schema migration and has a single-commit rollback path. ## Model Used OpenAI Codex, GPT-5, tool use and code execution. The runtime does not expose the context window size or reasoning mode. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
7c8064da1b
commit
5a1ce7aed8
11 files changed
+366
-13
No files matched your search
@@ -0,0 +1,58 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* Drift guard for the Docker build-stamp wiring.
|
||||
*
|
||||
* The server build runs scripts/write-build-stamp.mjs, which stamps the built
|
||||
* commit into dist/build-info.json. The build context has no .git, so the
|
||||
* script reads PAPERCLIP_BUILD_COMMIT instead. Docker exposes an ARG to the
|
||||
* next RUN as an environment variable, but an ARG goes out of scope at the end
|
||||
* of its stage. So the build stage must declare `ARG PAPERCLIP_BUILD_COMMIT`
|
||||
* before the server build; the production ARG alone stamps nothing, because
|
||||
* the server build already ran in the earlier stage.
|
||||
*
|
||||
* This guard fails if a refactor drops the build-stage ARG, moves it after the
|
||||
* server build, or removes the build-arg the docker workflow passes.
|
||||
*/
|
||||
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
|
||||
const dockerfile = readFileSync(path.join(repoRoot, "Dockerfile"), "utf8");
|
||||
const workflow = readFileSync(path.join(repoRoot, ".github", "workflows", "docker.yml"), "utf8");
|
||||
|
||||
/**
|
||||
* Return the text of the Dockerfile stage that starts at the named target.
|
||||
* A stage runs from its `FROM ... AS <name>` line to the next `FROM` line.
|
||||
*/
|
||||
function stageBody(source: string, stageName: string): string {
|
||||
const froms = [...source.matchAll(/^FROM .*$/gm)];
|
||||
const startIdx = froms.findIndex((m) => new RegExp(`\\bAS ${stageName}\\b`).test(m[0]));
|
||||
expect(startIdx, `Dockerfile must declare a '${stageName}' stage`).toBeGreaterThanOrEqual(0);
|
||||
const start = froms[startIdx].index ?? 0;
|
||||
const end = froms[startIdx + 1]?.index ?? source.length;
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
describe("docker build-stamp wiring", () => {
|
||||
it("declares PAPERCLIP_BUILD_COMMIT in the build stage before the server build", () => {
|
||||
const build = stageBody(dockerfile, "build");
|
||||
const argIdx = build.search(/^ARG PAPERCLIP_BUILD_COMMIT\b/m);
|
||||
const serverBuildIdx = build.search(/^RUN pnpm --filter @paperclipai\/server build\b/m);
|
||||
expect(argIdx, "build stage must declare ARG PAPERCLIP_BUILD_COMMIT").toBeGreaterThanOrEqual(0);
|
||||
expect(serverBuildIdx, "build stage must run the server build").toBeGreaterThanOrEqual(0);
|
||||
expect(
|
||||
argIdx,
|
||||
"ARG PAPERCLIP_BUILD_COMMIT must precede the server build so the stamp script reads it",
|
||||
).toBeLessThan(serverBuildIdx);
|
||||
});
|
||||
|
||||
it("passes PAPERCLIP_BUILD_COMMIT as a build-arg for both image targets", () => {
|
||||
const argLines = [...workflow.matchAll(/^\s*PAPERCLIP_BUILD_COMMIT=.*$/gm)];
|
||||
expect(
|
||||
argLines.length,
|
||||
"the docker workflow must pass PAPERCLIP_BUILD_COMMIT for the production and cloud builds",
|
||||
).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readGitCommit, resolveServiceVersion } from "../instrumentation.js";
|
||||
|
||||
describe("resolveServiceVersion", () => {
|
||||
it("prefers the build stamp over every other source", () => {
|
||||
expect(resolveServiceVersion("aaaaaaa", "bbbbbbb", "2026.5.0")).toBe("aaaaaaa");
|
||||
});
|
||||
|
||||
it("uses the runtime git commit when no build stamp exists", () => {
|
||||
expect(resolveServiceVersion(null, "bbbbbbb", "2026.5.0")).toBe("bbbbbbb");
|
||||
});
|
||||
|
||||
it("uses OTEL_SERVICE_VERSION when no stamp and no git commit exist", () => {
|
||||
expect(resolveServiceVersion(null, null, "2026.5.0")).toBe("2026.5.0");
|
||||
});
|
||||
|
||||
it("falls back to 'unknown' when every source is absent", () => {
|
||||
expect(resolveServiceVersion(null, null, undefined)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("treats an empty env value as absent", () => {
|
||||
expect(resolveServiceVersion(null, null, "")).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("readGitCommit", () => {
|
||||
it("resolves git from the module checkout, not the process launch directory", () => {
|
||||
// This test needs reachable git metadata in the checkout that holds the
|
||||
// module. Skip the assertion when the environment has no git.
|
||||
const baseline = readGitCommit();
|
||||
if (baseline === null) return;
|
||||
|
||||
const original = process.cwd();
|
||||
const launchDir = mkdtempSync(join(tmpdir(), "paperclip-no-git-"));
|
||||
try {
|
||||
// Move the process into a directory with no repository. The lookup still
|
||||
// returns the checkout commit, because it reads the module directory, not
|
||||
// the launch directory.
|
||||
process.chdir(launchDir);
|
||||
expect(readGitCommit()).toBe(baseline);
|
||||
} finally {
|
||||
process.chdir(original);
|
||||
rmSync(launchDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -5881,6 +5881,10 @@ describeEmbeddedPostgres("workspace runtime service control persistence", () =>
|
||||
|
||||
afterEach(async () => {
|
||||
await resetRuntimeServicesForTests();
|
||||
// Service control writes activity_log rows. Delete them before the company
|
||||
// delete so a lingering foreign-key row cannot block the company delete and
|
||||
// leak rows into the next test.
|
||||
await db.delete(activityLog);
|
||||
await db.delete(workspaceRuntimeServices);
|
||||
await db.delete(executionWorkspaces);
|
||||
await db.delete(projectWorkspaces);
|
||||
@@ -6915,6 +6919,11 @@ describeEmbeddedPostgres("workspace runtime startup reconciliation", () => {
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Startup reconciliation writes activity_log rows (for example, exposure
|
||||
// reservation drift). Delete those rows before the company delete. A stale
|
||||
// activity_log row holds a foreign key to the company and makes the company
|
||||
// delete fail, which leaks rows into the next test.
|
||||
await db.delete(activityLog);
|
||||
await db.delete(workspaceRuntimeServices);
|
||||
await db.delete(executionWorkspaces);
|
||||
await db.delete(projectWorkspaces);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveBuildCommit } from "../../scripts/write-build-stamp.mjs";
|
||||
|
||||
describe("resolveBuildCommit", () => {
|
||||
it("prefers the git commit over the supplied environment commit", () => {
|
||||
expect(resolveBuildCommit("aaaaaaa", "bbbbbbb")).toBe("aaaaaaa");
|
||||
});
|
||||
|
||||
it("falls back to PAPERCLIP_BUILD_COMMIT when git gives no commit", () => {
|
||||
// A Docker image build excludes `.git`, so the git lookup returns null. The
|
||||
// image build passes the commit in the environment instead.
|
||||
expect(resolveBuildCommit(null, "bbbbbbb")).toBe("bbbbbbb");
|
||||
});
|
||||
|
||||
it("trims the supplied commit", () => {
|
||||
expect(resolveBuildCommit(null, " bbbbbbb\n")).toBe("bbbbbbb");
|
||||
});
|
||||
|
||||
it("returns null when neither git nor the environment gives a commit", () => {
|
||||
expect(resolveBuildCommit(null, undefined)).toBe(null);
|
||||
});
|
||||
|
||||
it("treats an empty supplied commit as absent", () => {
|
||||
expect(resolveBuildCommit(null, "")).toBe(null);
|
||||
expect(resolveBuildCommit(null, " ")).toBe(null);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,8 @@
|
||||
// exit via `shutdownInstrumentation()`, which index.ts awaits in its signal
|
||||
// handler before `process.exit`.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
||||
@@ -354,6 +356,72 @@ async function importExporter(protocol: ExporterProtocol): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the commit SHA from the build stamp. The server `build` script writes
|
||||
* `dist/build-info.json` next to the compiled module. Return the SHA, or null
|
||||
* when the stamp is absent or unreadable. In `tsx` dev mode the module runs
|
||||
* from `src`, where no stamp exists, so this returns null and the caller falls
|
||||
* back to a runtime git lookup.
|
||||
*/
|
||||
export function readBuildStamp(): string | null {
|
||||
try {
|
||||
const stampUrl = new URL("./build-info.json", import.meta.url);
|
||||
const raw = readFileSync(stampUrl, "utf8");
|
||||
const parsed = JSON.parse(raw) as { commit?: unknown };
|
||||
if (typeof parsed.commit === "string" && parsed.commit.length > 0) {
|
||||
return parsed.commit;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the current commit SHA with `git rev-parse --short HEAD`. Return the
|
||||
* SHA, or null on any failure. This covers dev mode, where the process runs
|
||||
* from a git checkout. A missing `git` or a checkout with no `.git` returns
|
||||
* null and is not fatal.
|
||||
*
|
||||
* The lookup runs in the directory of this module, not the directory the
|
||||
* server process started in. `import.meta.url` points at `src` in dev mode and
|
||||
* `dist` in a built server; both sit inside the Paperclip checkout. A server
|
||||
* launched from an unrelated directory, or from inside another repository,
|
||||
* would otherwise report a wrong commit or fall back.
|
||||
*/
|
||||
export function readGitCommit(): string | null {
|
||||
try {
|
||||
const out = execFileSync("git", ["rev-parse", "--short", "HEAD"], {
|
||||
cwd: new URL("./", import.meta.url),
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
})
|
||||
.toString()
|
||||
.trim();
|
||||
return out.length > 0 ? out : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the `service.version` span attribute. The order is:
|
||||
* 1. The build stamp — the commit the running server was built from.
|
||||
* 2. A runtime git lookup — covers `tsx src/index.ts` dev mode.
|
||||
* 3. The `OTEL_SERVICE_VERSION` environment variable.
|
||||
* 4. "unknown".
|
||||
* The build stamp wins over the environment variable, so a stale
|
||||
* `OTEL_SERVICE_VERSION` cannot mask the true built commit. `OTEL_SERVICE_VERSION`
|
||||
* is a Paperclip-specific variable, not an OpenTelemetry SDK variable, so
|
||||
* Paperclip controls this precedence.
|
||||
*/
|
||||
export function resolveServiceVersion(
|
||||
buildStamp: string | null,
|
||||
gitCommit: string | null,
|
||||
envVersion: string | undefined,
|
||||
): string {
|
||||
return buildStamp || gitCommit || envVersion || "unknown";
|
||||
}
|
||||
|
||||
async function bootstrapOtel(endpoint: string): Promise<void> {
|
||||
const { protocol, packageName: exporterPackage } = resolveProtocol();
|
||||
|
||||
@@ -379,10 +447,19 @@ async function bootstrapOtel(endpoint: string): Promise<void> {
|
||||
const { resourceFromAttributes } = resources;
|
||||
const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = semconv;
|
||||
|
||||
const serviceVersion = resolveServiceVersion(
|
||||
readBuildStamp(),
|
||||
readGitCommit(),
|
||||
process.env.OTEL_SERVICE_VERSION,
|
||||
);
|
||||
// Log the resolved value once so an operator can confirm the built commit.
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[paperclip] OpenTelemetry service.version=${serviceVersion}`);
|
||||
|
||||
const sdk = new NodeSDK({
|
||||
resource: resourceFromAttributes({
|
||||
[ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || "paperclip",
|
||||
[ATTR_SERVICE_VERSION]: process.env.OTEL_SERVICE_VERSION || "unknown",
|
||||
[ATTR_SERVICE_VERSION]: serviceVersion,
|
||||
}),
|
||||
// For the HTTP protocols OTEL_EXPORTER_OTLP_ENDPOINT is a *base* URL
|
||||
// and the exporter appends /v1/traces only when it reads the env var
|
||||
|
||||
@@ -7702,19 +7702,29 @@ export async function reconcilePersistedRuntimeServicesOnStartup(db: Db) {
|
||||
}
|
||||
if (adoptedRecord) {
|
||||
const adoptedUrl = adoptedRecord.url ?? row.backendUrl ?? row.url ?? null;
|
||||
const adoptedHealthInput = {
|
||||
db,
|
||||
serviceName: row.serviceName,
|
||||
command: row.command,
|
||||
provider: "local_process",
|
||||
port: adoptedRecord.port ?? row.port,
|
||||
cwd: row.cwd,
|
||||
executionWorkspaceId: row.executionWorkspaceId ?? null,
|
||||
companyId: row.companyId,
|
||||
};
|
||||
// A surviving service can be slow to answer one probe when the host is
|
||||
// busy at startup. One timeout is not enough evidence to terminate it.
|
||||
// Confirm an unhealthy verdict with a second probe after a short bounded
|
||||
// delay, the same way the reuse path protects a shared runtime.
|
||||
let adoptedHealthy = await isRuntimeServiceUrlHealthy(adoptedUrl, adoptedHealthInput);
|
||||
if (!adoptedHealthy) {
|
||||
await delay(250);
|
||||
adoptedHealthy = await isRuntimeServiceUrlHealthy(adoptedUrl, adoptedHealthInput);
|
||||
}
|
||||
if (
|
||||
backfillDecision.action === "reprovision"
|
||||
|| !exposureHealthMatches
|
||||
|| !(await isRuntimeServiceUrlHealthy(adoptedUrl, {
|
||||
db,
|
||||
serviceName: row.serviceName,
|
||||
command: row.command,
|
||||
provider: "local_process",
|
||||
port: adoptedRecord.port ?? row.port,
|
||||
cwd: row.cwd,
|
||||
executionWorkspaceId: row.executionWorkspaceId ?? null,
|
||||
companyId: row.companyId,
|
||||
}))
|
||||
|| !adoptedHealthy
|
||||
) {
|
||||
if (backfillDecision.action === "reprovision") backfilled += 1;
|
||||
await terminateLocalService(adoptedRecord);
|
||||
|
||||
Reference in new issue
Block a user