diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 6e6cd0c604..26e0b0c824 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -7908,13 +7908,23 @@ void cbm_extract_definitions_without_module(CBMExtractCtx *ctx) { /* True when rel_path names a Blazor component file. */ static bool cbm_path_is_razor(const char *rel_path) { + /* Both Razor file types, not just components. `@page` is what DEFINES a + * Razor Page, so a .cshtml route is at least as worth extracting as a + * .razor one. Deliberately not .aspx/.ascx: Web Forms is a different + * templating syntax (`<%@ %>`, `runat="server"`) with no `@page` + * directive, so neither the C# recovery nor the scan below applies. */ if (!rel_path) { return false; } + static const char *const suffixes[] = {".razor", ".cshtml"}; size_t len = strlen(rel_path); - static const char suffix[] = ".razor"; - size_t slen = sizeof(suffix) - 1U; - return len > slen && strcmp(rel_path + (len - slen), suffix) == 0; + for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); i++) { + size_t slen = strlen(suffixes[i]); + if (len > slen && strcmp(rel_path + (len - slen), suffixes[i]) == 0) { + return true; + } + } + return false; } /* Match `@page "/route"` on ONE line; returns the route text or NULL. diff --git a/src/discover/language.c b/src/discover/language.c index a9b49b863e..b5ebd00a8b 100644 --- a/src/discover/language.c +++ b/src/discover/language.c @@ -55,6 +55,14 @@ static const ext_entry_t EXT_TABLE[] = { * parse_partial, which is why this is a best-effort mapping rather * than a dedicated grammar. */ {".razor", CBM_LANG_CSHARP}, + /* Razor Pages / MVC views. Same Razor syntax and the same C# host as + * .razor, and equally unmapped before this: an ASP.NET Core app's views + * produced no nodes at all. The `@page` directive that defines a Razor + * Page lives in this file type, so the route extraction below matters + * more here than it does for components. Best-effort on the same terms: + * the C# grammar recovers the @{ } / @functions blocks, the surrounding + * markup lands in ERROR regions and is reported via parse_partial. */ + {".cshtml", CBM_LANG_CSHARP}, /* Clojure */ {".clj", CBM_LANG_CLOJURE}, diff --git a/src/pipeline/fqn.c b/src/pipeline/fqn.c index b413727d5d..9d0861155e 100644 --- a/src/pipeline/fqn.c +++ b/src/pipeline/fqn.c @@ -282,20 +282,19 @@ static char *resolve_python_relative(char *buf, size_t buf_size, const char *mod return strdup(buf); } -/* Strip a trailing file extension from a segment (e.g. "helpers.ts" → "helpers"). - * Returns the new segment length. */ -static size_t strip_ext(const char *seg_start, size_t seg_len) { - const char *seg_end = seg_start + seg_len; - const char *dot = NULL; - for (const char *d = seg_end - FQN_SEP_LEN; d >= seg_start; d--) { - if (*d == '.') { - dot = d; - break; +/* Strip an explicit JS/TS module file extension while preserving dots that are + * part of an extensionless basename (e.g. "featureX.engine"). */ +static size_t strip_js_module_ext(const char *seg_start, size_t seg_len) { + static const char *const extensions[] = { + ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".json", + }; + for (size_t i = 0; i < sizeof(extensions) / sizeof(extensions[0]); i++) { + size_t ext_len = strlen(extensions[i]); + if (seg_len > ext_len && + memcmp(seg_start + seg_len - ext_len, extensions[i], ext_len) == 0) { + return seg_len - ext_len; } } - if (dot && dot > seg_start) { - return (size_t)(dot - seg_start); - } return seg_len; } @@ -322,7 +321,7 @@ static char *resolve_js_relative(char *buf, size_t buf_size, const char *module_ continue; } if (*p == '\0') { - seg_len = strip_ext(seg_start, seg_len); + seg_len = strip_js_module_ext(seg_start, seg_len); } if (seg_len > 0 && !path_append_segment(buf, buf_size, seg_start, seg_len)) { return NULL; diff --git a/src/pipeline/pass_pkgmap.c b/src/pipeline/pass_pkgmap.c index 3c4a1d338f..40e4c6c3f1 100644 --- a/src/pipeline/pass_pkgmap.c +++ b/src/pipeline/pass_pkgmap.c @@ -1397,7 +1397,11 @@ char *cbm_pipeline_resolve_module(const cbm_pipeline_ctx_t *ctx, const char *sou /* 1. Try relative import resolution (existing logic) */ char *resolved = cbm_pipeline_resolve_relative_import(source_rel, module_path); if (resolved) { - char *qn = cbm_pipeline_fqn_module(ctx->project_name, resolved); + /* The relative resolver has already removed an explicit JS/TS file + * extension. Treat the remaining path as a module path verbatim so a + * dotted extensionless basename such as `featureX.engine` is not + * stripped a second time by cbm_pipeline_fqn_module. */ + char *qn = cbm_pipeline_fqn_folder(ctx->project_name, resolved); free(resolved); return qn; } diff --git a/src/pipeline/registry.c b/src/pipeline/registry.c index 97c843355d..fa926d3c54 100644 --- a/src/pipeline/registry.c +++ b/src/pipeline/registry.c @@ -925,6 +925,87 @@ static const char *qualified_suffix_match(const qn_array_t *arr, const char *cal return match; } +/* A dotted callee whose FIRST segment starts upper-case names a type — URLSession, + * Calendar, JSONEncoder. That receiver chain is evidence the bare-name scorers + * throw away, and throwing it away binds Foundation's URLSession.shared.data to + * a project's own PickedFile.data: high confidence, and nothing in the graph + * shows it is wrong. Require instead that the candidate's own parent segment + * appears somewhere in the chain. Calendar.utcGregorian.startOfDayUTC resolving + * to AuthDTOs.Calendar.startOfDayUTC passes, because Calendar is in the chain. + * + * Only an upper-case first segment is guarded. A lower-case root names a value + * (vm.load, http.Get, os.path.join) whose declared type the chain does not + * show, so the chain proves nothing there and the call passes through + * unchanged. A callee with no separator passes through as well. + * + * Language agnostic by design: the registry holds no language, and every + * language that writes receiver chains gains the same protection. */ +static bool receiver_chain_admits(const char *callee_name, const char *candidate_qn) { + /* Normalize "::" -> "." so the chain composes with dotted candidate QNs, + * the same way qualified_suffix_match does. */ + char dotted[CBM_SZ_512]; + size_t w = 0; + for (const char *s = callee_name; *s && w + SKIP_ONE < sizeof(dotted);) { + if (s[0] == ':' && s[1] == ':') { + dotted[w++] = '.'; + s += 2; + } else { + dotted[w++] = *s++; + } + } + dotted[w] = '\0'; + + const char *last_dot = strrchr(dotted, '.'); + if (!last_dot) { + return true; /* bare name — no receiver chain to judge */ + } + if (dotted[0] < 'A' || dotted[0] > 'Z') { + return true; /* lower-case root names a value, not a type */ + } + /* A name written in capitals with underscores is a constant holding a + * value, not a type: ISO_4217_URL.lower is a string's own method. JSON and + * URL carry no underscore and stay guarded. */ + int has_underscore = 0; + int all_caps = 1; + for (const char *c = dotted; c < last_dot && *c != '.'; c++) { + if (*c == '_') { + has_underscore = 1; + } else if (*c >= 'a' && *c <= 'z') { + all_caps = 0; + break; + } + } + if (all_caps && has_underscore) { + return true; + } + + /* The candidate's parent segment: the one before its final name. */ + const char *cand_last = strrchr(candidate_qn, '.'); + if (!cand_last || cand_last == candidate_qn) { + return true; /* top-level candidate — no parent to look for */ + } + const char *parent = cand_last; + while (parent > candidate_qn && parent[-1] != '.') { + parent--; + } + size_t parent_len = (size_t)(cand_last - parent); + + /* Walk the chain — every segment before the final callee name. A trailing + * "()" is dropped so JSONEncoder().encode reads as JSONEncoder. */ + for (const char *seg = dotted; seg < last_dot;) { + const char *end = strchr(seg, '.'); + size_t len = (size_t)(end - seg); + if (len >= 2 && seg[len - 2] == '(' && seg[len - 1] == ')') { + len -= 2; /* an empty "()" — JSONEncoder().encode names JSONEncoder */ + } + if (len == parent_len && strncmp(seg, parent, parent_len) == 0) { + return true; + } + seg = end + SKIP_ONE; + } + return false; +} + /* Strategy 3+4: Name lookup + suffix match */ static cbm_resolution_t resolve_name_lookup(const cbm_registry_t *r, const char *callee_name, const char *module_qn, const char **import_vals, @@ -950,6 +1031,9 @@ static cbm_resolution_t resolve_name_lookup(const cbm_registry_t *r, const char /* Strategy 3: unique name */ if (arr->count == SKIP_ONE) { + if (!receiver_chain_admits(callee_name, arr->items[0])) { + return empty_result(); + } double conf = CONF_UNIQUE_NAME; if (import_vals && import_count > 0 && !is_import_reachable(arr->items[0], import_vals, import_count)) { @@ -964,6 +1048,9 @@ static cbm_resolution_t resolve_name_lookup(const cbm_registry_t *r, const char } const char *best = best_by_import_distance((const char **)arr->items, arr->count, module_qn); if (best) { + if (!receiver_chain_admits(callee_name, best)) { + return empty_result(); + } double conf = candidate_count_penalty(CONF_SUFFIX_MATCH, arr->count); return (cbm_resolution_t){best, "suffix_match", conf, arr->count}; } diff --git a/src/traces/traces.c b/src/traces/traces.c index f10eae2493..0919d3b770 100644 --- a/src/traces/traces.c +++ b/src/traces/traces.c @@ -6,6 +6,8 @@ #include "foundation/constants.h" enum { TRACE_PATH_SLASHES = 3, TRACE_NOT_FOUND = -1 }; +#include +#include #include #include #include @@ -63,6 +65,38 @@ const char *cbm_extract_path_from_url(const char *url, char *buf, size_t buf_sz) /* ── parseDuration ───────────────────────────────────────────────── */ +/* Read one nanosecond timestamp. Answers false for text that does not read + * cleanly from its first character to its last, the way src/main.c:1104 does + * it: an end pointer says where the read stopped, errno catches a number too + * large, and *end == '\0' catches anything left over. A leading blank is + * refused too, because strtoll would otherwise step over it. */ +static bool trace_read_nano(const char *text, int64_t *out) { + if (!text || !text[0] || isspace((unsigned char)text[0])) { + return false; + } + char *end = NULL; + errno = 0; + long long value = strtoll(text, &end, CBM_DECIMAL_BASE); + if (errno != 0 || !end || end == text || *end != '\0') { + return false; + } + *out = (int64_t)value; + return true; +} + +int64_t cbm_parse_duration_checked(const char *start_nano, const char *end_nano, bool *ok) { + int64_t start = 0; + int64_t end = 0; + bool read_both = trace_read_nano(start_nano, &start) && trace_read_nano(end_nano, &end); + if (ok) { + *ok = read_both; + } + if (!read_both) { + return 0; + } + return (end > start) ? (end - start) : 0; +} + int64_t cbm_parse_duration(const char *start_nano, const char *end_nano) { if (!start_nano || !end_nano) { return 0; @@ -115,7 +149,14 @@ bool cbm_extract_http_info(const cbm_trace_span_t *span, const char *service_nam return false; } - out->duration_ns = cbm_parse_duration(span->start_time, span->end_time); + /* A timestamp nobody can read is not a measurement. It used to read as 0, + * so an unreadable START time reported the whole end time as the duration + * -- a made-up number that looks like a real one. The HTTP method and path + * on this span are still good, so the span is still returned and only the + * duration says it is missing. */ + bool timed = false; + int64_t duration = cbm_parse_duration_checked(span->start_time, span->end_time, &timed); + out->duration_ns = timed ? duration : CBM_DURATION_UNKNOWN; return true; } diff --git a/src/traces/traces.h b/src/traces/traces.h index ff628e44d6..3f18e37ea4 100644 --- a/src/traces/traces.h +++ b/src/traces/traces.h @@ -43,6 +43,8 @@ typedef struct { const char *path; const char *status_code; int span_kind; + /* Nanoseconds, or CBM_DURATION_UNKNOWN when the span's timestamps could + * not be read. A duration of 0 means the span really took no time. */ int64_t duration_ns; } cbm_http_span_info_t; @@ -62,9 +64,20 @@ bool cbm_extract_http_info(const cbm_trace_span_t *span, const char *service_nam * Writes to buf (up to buf_sz). Returns buf, or "" if not a valid URL. */ const char *cbm_extract_path_from_url(const char *url, char *buf, size_t buf_sz); -/* Parse nanosecond timestamp strings and return duration. */ +/* A duration nobody could measure. Kept apart from 0, which is a real span + * that took no time. */ +#define CBM_DURATION_UNKNOWN (-1) + +/* Parse nanosecond timestamp strings and return duration. Text that cannot be + * read counts as 0, so an unreadable timestamp and a span that took no time + * give the same answer. Use cbm_parse_duration_checked when that matters. */ int64_t cbm_parse_duration(const char *start_nano, const char *end_nano); +/* Same, and also says whether both timestamps could be read. *ok is false for + * a NULL argument and for any text that does not read cleanly end to end, so + * a caller can tell "took no time" from "nobody could measure this". */ +int64_t cbm_parse_duration_checked(const char *start_nano, const char *end_nano, bool *ok); + /* Calculate P99 from an array of int64_t values. * Sorts values in-place. Returns 0 for empty array. */ int64_t cbm_calculate_p99(int64_t *values, int count); diff --git a/tests/test_edge_imports.c b/tests/test_edge_imports.c index bf99e8d428..51b1423440 100644 --- a/tests/test_edge_imports.c +++ b/tests/test_edge_imports.c @@ -365,6 +365,96 @@ TEST(ei_typescript_named_relative_import) { PASS(); } +/* #1682: extensionless dotted basenames are part of the module name. The + * resolver used to strip `.engine`, miss the module, and bind both imports to + * the same-named fixture Function in the sibling spec file. */ +TEST(ei_typescript_dotted_relative_import_targets_source_module_issue1682) { + static const char *engine_path = "packages/api/src/modules/featureX/featureX.engine.ts"; + static const char *consumer_path = "packages/api/src/modules/consumer/consumer.service.ts"; + static const EILangFile f[] = { + {"packages/api/src/modules/featureX/featureX.engine.ts", + "export interface SomeType { id: string; qty: number; }\n" + "export interface Evaluation { rateByItem: Record; }\n" + "export function helperB(configs: SomeType[], lines: SomeType[]): Evaluation {\n" + " return { rateByItem: { [lines[0].id]: lines[0].qty + configs.length } };\n" + "}\n"}, + {"packages/api/src/modules/featureX/featureX.service.ts", + "import { SomeType, Evaluation, helperB } from './featureX.engine';\n" + "export class FeatureXService {\n" + " evaluate(configs: SomeType[], lines: SomeType[]): Evaluation {\n" + " return helperB(configs, lines);\n" + " }\n" + "}\n"}, + {"packages/api/src/modules/featureX/featureX.service.spec.ts", + "import { SomeType, helperB } from './featureX.engine';\n" + "function featureX(overrides: Partial): SomeType {\n" + " return { id: 'x', qty: 1, ...overrides };\n" + "}\n" + "export function exerciseFixture(): number {\n" + " return helperB([featureX({})], [featureX({ qty: 2 })]).rateByItem.x;\n" + "}\n"}, + {"packages/api/src/modules/consumer/consumer.service.ts", + "import { helperB, type SomeType } from '../featureX/featureX.engine';\n" + "export class ConsumerService {\n" + " callerMethod(items: SomeType[]): number {\n" + " return helperB(items, [{ id: 'p1', qty: 1 }]).rateByItem.p1;\n" + " }\n" + "}\n"}, + {"packages/mobile/src/api.ts", + "export function helperB(token: string): Promise {\n" + " return fetch('/api/x', { method: 'POST', body: token });\n" + "}\n"}, + }; + + EILangProj lp; + cbm_store_t *store = ei_index_files(&lp, f, (int)(sizeof(f) / sizeof(f[0]))); + ASSERT_NOT_NULL(store); + + int64_t consumer_id = ei_node_id_for_file_label(store, lp.project, consumer_path, "File"); + ASSERT_GT(consumer_id, 0); + + cbm_edge_t *edges = NULL; + int edge_count = 0; + ASSERT_EQ( + cbm_store_find_edges_by_source_type(store, consumer_id, "IMPORTS", &edges, &edge_count), + CBM_STORE_OK); + + bool saw_helper = false; + bool saw_type = false; + bool helper_target_ok = false; + bool type_target_ok = false; + for (int i = 0; i < edge_count; i++) { + const char *props = edges[i].properties_json ? edges[i].properties_json : ""; + bool is_helper = strstr(props, "\"local_name\":\"helperB\"") != NULL; + bool is_type = strstr(props, "\"local_name\":\"SomeType\"") != NULL; + if (!is_helper && !is_type) { + continue; + } + + cbm_node_t *target = (cbm_node_t *)calloc(1, sizeof(cbm_node_t)); + ASSERT_NOT_NULL(target); + ASSERT_EQ(cbm_store_find_node_by_id(store, edges[i].target_id, target), CBM_STORE_OK); + bool target_ok = target->file_path && strcmp(target->file_path, engine_path) == 0; + if (is_helper) { + saw_helper = true; + helper_target_ok = target_ok; + } + if (is_type) { + saw_type = true; + type_target_ok = target_ok; + } + cbm_store_free_nodes(target, 1); + } + cbm_store_free_edges(edges, edge_count); + ei_cleanup(&lp, store); + + ASSERT_TRUE(saw_helper); + ASSERT_TRUE(saw_type); + ASSERT_TRUE(helper_target_ok); + ASSERT_TRUE(type_target_ok); + PASS(); +} + /* TypeScript: default import `import helper from './util'`. */ TEST(ei_typescript_default_import) { static const EILangFile f[] = { @@ -1063,6 +1153,7 @@ SUITE(edge_imports) { /* ── GREEN GUARDS — TypeScript (must stay passing) ── */ RUN_TEST(ei_typescript_named_relative_import); + RUN_TEST(ei_typescript_dotted_relative_import_targets_source_module_issue1682); RUN_TEST(ei_typescript_default_import); RUN_TEST(ei_typescript_namespace_import); RUN_TEST(ei_typescript_aliased_import); diff --git a/tests/test_extraction.c b/tests/test_extraction.c index 7ea702c3a3..b3232f0e50 100644 --- a/tests/test_extraction.c +++ b/tests/test_extraction.c @@ -4045,6 +4045,51 @@ TEST(extract_blazor_component_without_page_has_no_route) { PASS(); } +/* Razor Pages: `@page` is what turns a .cshtml view INTO a page — it is the + * defining directive of the model, not an optional annotation as it is on a + * Blazor component. So an ASP.NET Core app's routable surface lives entirely + * in file types that were unmapped until now, and every one of those routes + * was invisible. + * + * Same mechanism as the .razor case: the directive sits in markup above any + * code block, where the C# grammar never reaches, so it is read from raw + * source and hangs off the file's Module definition. */ +TEST(extract_razor_page_directive_routes_cshtml_view) { + CBMFileResult *r = extract("@page \"/orders\"\n" + "@model OrderIndexModel\n" + "\n" + "

Orders

\n" + "
@Model.Count
\n", + CBM_LANG_CSHARP, "t", "Pages/Orders/Index.cshtml"); + ASSERT_NOT_NULL(r); + const CBMDefinition *mod = find_module_def(r); + ASSERT_NOT_NULL(mod); + ASSERT_NOT_NULL(mod->route_path); + ASSERT_STR_EQ(mod->route_path, "/orders"); + /* A Razor Page is reached by navigation, i.e. GET — same as a component. */ + ASSERT_NOT_NULL(mod->route_method); + ASSERT_STR_EQ(mod->route_method, "GET"); + cbm_free_result(r); + PASS(); +} + +/* The overwhelming majority of .cshtml files are layouts, partials and views + * with no `@page` at all. If the scan fired on those, an ASP.NET app would + * gain a bogus Route node per view — worse than the missing routes it set out + * to fix, because a wrong route looks authoritative. */ +TEST(extract_razor_layout_without_page_has_no_route) { + CBMFileResult *r = extract("@model LayoutModel\n" + "\n" + "@RenderBody()\n", + CBM_LANG_CSHARP, "t", "Pages/Shared/_Layout.cshtml"); + ASSERT_NOT_NULL(r); + const CBMDefinition *mod = find_module_def(r); + ASSERT_NOT_NULL(mod); + ASSERT_NULL(mod->route_path); + cbm_free_result(r); + PASS(); +} + /* A comment between decorators must not drop the decorators above it. * Comments are NAMED tree-sitter nodes, so the prev-sibling walk used to stop * at one — a documented route (@Post + @HttpCode above an explanatory comment) @@ -7208,6 +7253,8 @@ SUITE(extraction) { RUN_TEST(extract_java_jaxrs_path_composition_issue1005); RUN_TEST(extract_blazor_page_directive_routes_component); RUN_TEST(extract_blazor_component_without_page_has_no_route); + RUN_TEST(extract_razor_page_directive_routes_cshtml_view); + RUN_TEST(extract_razor_layout_without_page_has_no_route); RUN_TEST(extract_ts_template_string_url_issue1006); RUN_TEST(extract_go_binary_concat_url_issue1249); RUN_TEST(extract_go_binary_concat_url_no_literal_suffix_issue1249); diff --git a/tests/test_fqn.c b/tests/test_fqn.c index 5d565f8d8c..f9d17fa0c3 100644 --- a/tests/test_fqn.c +++ b/tests/test_fqn.c @@ -84,6 +84,21 @@ TEST(fqn_module_qn_still_strips_extension) { PASS(); } +TEST(fqn_relative_js_import_preserves_dotted_basename_issue1682) { + ASSERT_FQN( + cbm_pipeline_resolve_relative_import( + "packages/api/src/modules/consumer/consumer.service.ts", "../featureX/featureX.engine"), + "packages/api/src/modules/featureX/featureX.engine"); + ASSERT_FQN( + cbm_pipeline_resolve_relative_import("packages/api/src/modules/moduleA/moduleA.service.ts", + "../moduleQ/moduleQ.service"), + "packages/api/src/modules/moduleQ/moduleQ.service"); + ASSERT_FQN(cbm_pipeline_resolve_relative_import( + "packages/api/src/modules/moduleA/moduleA.service.ts", "./create-thing.dto"), + "packages/api/src/modules/moduleA/create-thing.dto"); + PASS(); +} + TEST(fqn_compute_basic_rs) { ASSERT_FQN(cbm_pipeline_fqn_compute("proj", "lib.rs", "new"), "proj.lib.new"); PASS(); @@ -665,6 +680,7 @@ SUITE(fqn) { RUN_TEST(fqn_file_qn_preserves_dotfile_variants_issue1077); RUN_TEST(fqn_file_qn_distinguishes_same_stem_header_source_issue964); RUN_TEST(fqn_module_qn_still_strips_extension); + RUN_TEST(fqn_relative_js_import_preserves_dotted_basename_issue1682); RUN_TEST(fqn_compute_basic_rs); RUN_TEST(fqn_compute_file_sibling_distinct); RUN_TEST(fqn_compute_symbol_still_strips); diff --git a/tests/test_language.c b/tests/test_language.c index 1bcd5e0402..20529108f6 100644 --- a/tests/test_language.c +++ b/tests/test_language.c @@ -97,6 +97,12 @@ TEST(lang_ext_razor) { ASSERT_EQ(cbm_language_for_extension(".razor"), CBM_LANG_CSHARP); PASS(); } +/* Razor Pages / MVC views were unmapped for the same reason .razor was, so an + * ASP.NET Core app's entire view layer was invisible to discovery. */ +TEST(lang_ext_cshtml) { + ASSERT_EQ(cbm_language_for_extension(".cshtml"), CBM_LANG_CSHARP); + PASS(); +} TEST(lang_ext_php) { ASSERT_EQ(cbm_language_for_extension(".php"), CBM_LANG_PHP); PASS(); @@ -1206,6 +1212,7 @@ SUITE(language) { RUN_TEST(lang_ext_ixx); RUN_TEST(lang_ext_csharp); RUN_TEST(lang_ext_razor); + RUN_TEST(lang_ext_cshtml); RUN_TEST(lang_ext_php); RUN_TEST(lang_ext_lua); RUN_TEST(lang_ext_scala); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index c5d3a95393..d83d4b205a 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -9456,6 +9456,78 @@ TEST(registry_confidence_suffix_match) { PASS(); } +/* Issue #1893: a call on a library type bound to a same-named project member. + * URLSession is Foundation's, not this project's, so PickedFile.data is the + * wrong target — and with one candidate it won the top name-only confidence. */ +TEST(registry_receiver_chain_refuses_library_unique_name_issue1893) { + cbm_registry_t *reg = cbm_registry_new(); + cbm_registry_add(reg, "data", "HomeboxUI.PickedFile.data", "Variable"); + + cbm_resolution_t r = + cbm_registry_resolve(reg, "URLSession.shared.data", "HomeboxUI.Net", NULL, NULL, 0); + ASSERT_NULL(r.qualified_name); + + cbm_registry_free(reg); + PASS(); +} + +/* The same refusal on the other name-only exit, where several candidates share + * the final name and import distance picks the winner. */ +TEST(registry_receiver_chain_refuses_library_suffix_match_issue1893) { + cbm_registry_t *reg = cbm_registry_new(); + cbm_registry_add(reg, "data", "HomeboxUI.PickedFile.data", "Variable"); + cbm_registry_add(reg, "data", "HomeboxUI.Payload.data", "Variable"); + + cbm_resolution_t r = + cbm_registry_resolve(reg, "URLSession.shared.data", "HomeboxUI.Net", NULL, NULL, 0); + ASSERT_NULL(r.qualified_name); + + cbm_registry_free(reg); + PASS(); +} + +/* The true positive the gate must not eat: the project extends Calendar itself, + * so Calendar really is in the receiver chain. */ +TEST(registry_receiver_chain_keeps_project_extension_issue1893) { + cbm_registry_t *reg = cbm_registry_new(); + cbm_registry_add(reg, "startOfDayUTC", "AuthDTOs.Calendar.startOfDayUTC", "Method"); + + cbm_resolution_t r = cbm_registry_resolve(reg, "Calendar.utcGregorian.startOfDayUTC", + "HomeboxUI.Stats", NULL, NULL, 0); + ASSERT_STR_EQ(r.qualified_name, "AuthDTOs.Calendar.startOfDayUTC"); + ASSERT_STR_EQ(r.strategy, "unique_name"); + + cbm_registry_free(reg); + PASS(); +} + +/* A lower-case root names a value, whose type the chain does not show. The gate + * must not look at it, or every ordinary vm.load style call would be refused. */ +TEST(registry_receiver_chain_ignores_lowercase_root_issue1893) { + cbm_registry_t *reg = cbm_registry_new(); + cbm_registry_add(reg, "load", "HomeboxUI.EntityListViewModel.load", "Method"); + + cbm_resolution_t r = cbm_registry_resolve(reg, "vm.load", "HomeboxUI.Views", NULL, NULL, 0); + ASSERT_STR_EQ(r.qualified_name, "HomeboxUI.EntityListViewModel.load"); + ASSERT_STR_EQ(r.strategy, "unique_name"); + + cbm_registry_free(reg); + PASS(); +} + +/* An unqualified callee has no chain at all and must pass through unchanged. */ +TEST(registry_receiver_chain_ignores_bare_name_issue1893) { + cbm_registry_t *reg = cbm_registry_new(); + cbm_registry_add(reg, "helper", "proj.pkg.helper", "Function"); + + cbm_resolution_t r = cbm_registry_resolve(reg, "helper", "proj.other", NULL, NULL, 0); + ASSERT_STR_EQ(r.qualified_name, "proj.pkg.helper"); + ASSERT_STR_EQ(r.strategy, "unique_name"); + + cbm_registry_free(reg); + PASS(); +} + TEST(registry_fuzzy_confidence_single) { cbm_registry_t *reg = cbm_registry_new(); cbm_registry_add(reg, "Handler", "proj.svc.Handler", "Function"); @@ -13491,6 +13563,11 @@ SUITE(pipeline) { RUN_TEST(registry_confidence_same_module); RUN_TEST(registry_confidence_unique_name); RUN_TEST(registry_confidence_suffix_match); + RUN_TEST(registry_receiver_chain_refuses_library_unique_name_issue1893); + RUN_TEST(registry_receiver_chain_refuses_library_suffix_match_issue1893); + RUN_TEST(registry_receiver_chain_keeps_project_extension_issue1893); + RUN_TEST(registry_receiver_chain_ignores_lowercase_root_issue1893); + RUN_TEST(registry_receiver_chain_ignores_bare_name_issue1893); RUN_TEST(registry_fuzzy_confidence_single); RUN_TEST(registry_fuzzy_confidence_distance); RUN_TEST(registry_negative_import_rejects); diff --git a/tests/test_traces.c b/tests/test_traces.c index 18d02a90d3..efae8918f2 100644 --- a/tests/test_traces.c +++ b/tests/test_traces.c @@ -265,6 +265,82 @@ TEST(traces_parse_duration_large_values) { PASS(); } +/* A timestamp the code cannot read is not a measurement of no time. + * + * strtoll answers 0 for text it cannot read, and the subtraction guard turns + * that into a duration of 0 ns. A span that genuinely took no time and a span + * whose timestamps were garbage then look the same, and no later query can + * tell them apart. cbm_parse_duration_checked reports which one it read. */ +TEST(traces_parse_duration_checked_reports_unreadable_timestamps) { + bool ok = false; + + /* Positive control: a good pair still reads, and still answers the same + * number cbm_parse_duration answers. */ + int64_t d = cbm_parse_duration_checked("1000000000", "1050000000", &ok); + ASSERT(ok); + ASSERT_EQ(d, 50000000); + + /* A real measurement of no time reads fine. Zero is an answer here. */ + ok = false; + d = cbm_parse_duration_checked("5000000000", "5000000000", &ok); + ASSERT(ok); + ASSERT_EQ(d, 0); + + /* End before start reads fine too. The clamp to 0 is the caller's rule, + * not a reading failure. */ + ok = false; + d = cbm_parse_duration_checked("1000", "500", &ok); + ASSERT(ok); + ASSERT_EQ(d, 0); + + /* The claim: text that does not read is reported, not folded into 0. */ + const char *unreadable[] = {"abc", "", " 100", "100ns", "1e9"}; + for (size_t i = 0; i < sizeof(unreadable) / sizeof(unreadable[0]); i++) { + ok = true; + (void)cbm_parse_duration_checked(unreadable[i], "1050000000", &ok); + ASSERT(!ok); + ok = true; + (void)cbm_parse_duration_checked("1000000000", unreadable[i], &ok); + ASSERT(!ok); + } + + /* A NULL argument was never a measurement either. */ + ok = true; + (void)cbm_parse_duration_checked(NULL, "1000", &ok); + ASSERT(!ok); + ok = true; + (void)cbm_parse_duration_checked("1000", NULL, &ok); + ASSERT(!ok); + PASS(); +} + +/* A span whose timestamps cannot be read keeps its method and path, and says + * the duration was not recorded rather than claiming it was zero. */ +TEST(traces_extract_http_info_marks_unreadable_duration) { + cbm_trace_attr_t attrs[] = { + {.key = "http.method", .string_value = "GET"}, + {.key = "http.route", .string_value = "/api/orders"}, + {.key = "http.status_code", .string_value = "200"}, + }; + cbm_trace_span_t span = { + .kind = 2, + .attributes = attrs, + .attr_count = 3, + .start_time = "not-a-timestamp", + .end_time = "1050000000", + }; + + cbm_http_span_info_t info; + bool ok = cbm_extract_http_info(&span, "svc", &info); + /* The HTTP part of the span is still good data, so it is still returned. */ + ASSERT(ok); + ASSERT_STR_EQ(info.method, "GET"); + ASSERT_STR_EQ(info.path, "/api/orders"); + /* The claim: not recorded, rather than a duration of zero. */ + ASSERT_EQ(info.duration_ns, CBM_DURATION_UNKNOWN); + PASS(); +} + /* ── TestCalculateP99 — edge cases ────────────────────────────────── */ TEST(traces_calculate_p99_100_values) { @@ -341,4 +417,6 @@ SUITE(traces) { RUN_TEST(traces_parse_duration_both_null); RUN_TEST(traces_parse_duration_equal); RUN_TEST(traces_parse_duration_large_values); + RUN_TEST(traces_parse_duration_checked_reports_unreadable_timestamps); + RUN_TEST(traces_extract_http_info_marks_unreadable_duration); }