-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelease_database.qmd
More file actions
2033 lines (1811 loc) · 92.2 KB
/
Copy pathrelease_database.qmd
File metadata and controls
2033 lines (1811 loc) · 92.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Release CalCOFI Database"
calcofi:
target_name: release_database
workflow_type: release
dependency:
- auto
# a small file ONLY this notebook writes — never the data/releases
# directory, which test_release.qmd also writes into (see the `cleanup`
# chunk); that shared ownership made this target permanently outdated.
output: data/releases/_release_stamp.json
# cross-dataset foreign keys (relationships spanning ingests) are authored in
# metadata/relationships_cross.csv; intra-dataset FKs live in each ingest's
# relationships.json. both are merged below into the release relationships.json.
# ERD color overrides for common/cross-cutting tables (neutral). dataset
# colors themselves come from each ingest's calcofi.erd.color.
erd_overrides:
dataset: "#e8e8e8"
measurement_type: "#e8e8e8"
cruise: "#e8e8e8"
sample: "#e8e8e8"
obs: "#e8e8e8"
obs_attribute: "#e8e8e8"
sample_measurement: "#e8e8e8"
obs_ctd_full: "#e8e8e8"
obs_mets_full: "#e8e8e8"
spatial: "#cfe8ea"
spatial_attribute: "#cfe8ea"
execute:
echo: true
message: true
warning: true
editor_options:
chunk_output_type: console
format:
html:
code-fold: true
editor:
markdown:
wrap: 72
---
## Overview {.unnumbered}
**Goal**: Create a frozen (immutable) release of the CalCOFI integrated
database by assembling all ingest parquet outputs. This is the "caboose"
notebook that always runs last, after all ingest notebooks complete.
**Upstream notebooks** are auto-discovered from `calcofi:` YAML
frontmatter in each `.qmd`. All workflows with `workflow_type: ingest`
or `spatial` feed into this release notebook via `dependency: [auto]`
in `_targets.R`.
```{r}
#| label: gen_fig_workflow
#| results: asis
#| echo: false
#| message: false
#| warning: false
# echo must stay false: this chunk emits a ```{mermaid} cell, and echoing R
# source that contains literal ``` fences would corrupt the document structure.
librarian::shelf(targets, quiet = TRUE)
# auto-discover the pipeline graph straight from _targets.R, so newly added
# workflows show up without editing this diagram. callr_function = NULL keeps it
# in-process (safe when this notebook is rendered via tar_make); outdated = FALSE
# skips the up-to-date check (no node status needed here).
invisible(suppressMessages(capture.output(
net <- tar_network(targets_only = TRUE, outdated = FALSE, callr_function = NULL))))
nodes <- net$vertices$name
edges <- net$edges
# group each node by name so the diagram colors input / ingest / release / test
node_grp <- ifelse(nodes == "release_database", "rel",
ifelse(nodes == "test_release", "test",
ifelse(nodes == "corrections_csv", "input", "ingest")))
# emit Mermaid source; rendered client-side by mermaid.js (the project-level
# `mermaid-format: png` is disabled — it routed this through headless Chrome,
# which hung intermittently; see _quarto.yml). release_database (this notebook)
# is highlighted.
mmd <- c(
"flowchart LR",
vapply(nodes, function(n) sprintf(' %s["%s"]', n, n), ""),
apply(edges, 1, function(r) sprintf(" %s --> %s", r[["from"]], r[["to"]])),
" classDef input fill:#eeeeee,stroke:#999999,color:#333333;",
" classDef ingest fill:#e3f2fd,stroke:#1565c0,color:#0d3c61;",
" classDef rel fill:#ef6c00,stroke:#b35100,color:#ffffff,font-weight:bold;",
" classDef test fill:#e8f4e8,stroke:#2e7d32,color:#1b5e20;")
for (grp in c("input", "ingest", "rel", "test")) {
members <- nodes[node_grp == grp]
if (length(members))
mmd <- c(mmd, sprintf(" class %s %s;", paste(members, collapse = ","), grp))
}
cap <- paste(
"Pipeline dependency graph, auto-discovered from `_targets.R`: every workflow",
"in this folder is a node and edges are dependencies. `release_database` (this",
"notebook, orange) is the caboose — it runs last, after all ingests, to assemble",
"the frozen release. Click to zoom.")
cat("```{mermaid}\n")
cat("%%| label: fig-workflow\n")
cat('%%| fig-cap: "', cap, '"\n', sep = "")
cat(mmd, sep = "\n")
cat("\n```\n")
```
## Setup
```{r}
#| label: setup
devtools::load_all(here::here("../calcofi4db"))
devtools::load_all(here::here("../calcofi4r"))
# cleanup_gcs_obsolete(dry_run = F)
librarian::shelf(
CalCOFI / calcofi4db,
CalCOFI / calcofi4r,
DBI,
dplyr,
DT,
fs,
glue,
here,
jsonlite,
purrr,
tibble,
quiet = T
)
options(DT.options = list(scrollX = TRUE))
# release version
release_version <- format(Sys.Date(), "v%Y.%m.%d")
message(glue("Release version: {release_version}"))
# --- refuse to re-cut the version consumers are currently reading -------------
#
# The version is the DATE, so two runs on one day reuse the tag — and the second
# overwrites `gs://…/releases/{version}/` in place. That is how v2026.08.10 was
# republished on 2026-08-11 with data that then FAILED test_release: promotion
# was correctly withheld, but promotion was never needed, because `latest.txt`
# already pointed at the path being overwritten. Consumers reading `latest` got
# unverified data without a single byte of `latest.txt` changing.
#
# The gate everyone relies on ("a failing release is not promoted") silently does
# not hold when the version does not change. So: if this run would overwrite the
# currently-promoted release, stop. Re-cutting a version nobody is reading is
# fine and stays unguarded.
#
# Override deliberately with CALCOFI_ALLOW_REPUBLISH=TRUE when the intent really
# is to replace a promoted release in place (and accept that consumers see the
# new bytes before any test has passed).
# Read the pointer through the authenticated API, NOT
# https://storage.googleapis.com/.../latest.txt — that URL is CDN-cached, and
# this guard consumed it for months. On 2026-08-14 the cache made it wrong in
# both directions within an hour: it false-fired on a re-cut after a rollback
# (harmless), and — the direction that matters — for an hour after any promotion
# the cache still shows the PREVIOUS version, so this comparison concludes
# `latest.txt` points elsewhere and lets a run overwrite the release consumers
# are actively reading. A guard that fails open for an hour after every
# promotion is worse than no guard, because it reads as protection.
promoted <- calcofi4db::read_promoted_release(bucket = "calcofi-db")
if (!is.na(promoted) && identical(promoted, release_version) &&
!isTRUE(as.logical(Sys.getenv("CALCOFI_ALLOW_REPUBLISH", "FALSE"))))
stop(glue(
"release {release_version} is the version `latest.txt` currently points at, ",
"so cutting it again would overwrite what consumers are reading — before any ",
"test has run against the new bytes.\n",
" Wait for the date to roll over, or set CALCOFI_ALLOW_REPUBLISH=TRUE if ",
"replacing the promoted release in place is genuinely what you want."))
```
## Assemble from Ingest Outputs
Create VIEWs on local parquet files from each ingest (zero-copy).
For tables appearing in multiple ingests, use the canonical (first) source.
```{r}
#| label: assemble_working
con_wdl <- get_duckdb_con(":memory:")
load_duckdb_extension(con_wdl, "spatial")
# auto-discover table registry from all ingest manifests. An ingest that declares
# `in_release: false` in its calcofi: YAML block is skipped everywhere below: it
# still runs in the pipeline and writes its own data/parquet/{dataset}/ outputs,
# but nothing of it reaches the frozen release. That is how a dataset under
# review (currently cdfw_dungeness-crab) is staged without leaking into a release.
ds_excluded <- release_excluded_datasets(here())
if (length(ds_excluded))
message(glue("Held out of this release (in_release: false): ",
"{paste(ds_excluded, collapse = ', ')}"))
# keep only the data/parquet/* dirs that belong in the release — used by the
# relationships.json / metadata.json / manifest.json globs further down
in_release_dirs <- function(paths)
paths[!basename(dirname(paths)) %in% ds_excluded]
registry <- build_release_table_registry(here())
# The consolidated core is now emitted per-dataset: every ingest writes its own
# `sample`/`obs`/… shard. The registry marks the FIRST ingest supplying a table
# name as canonical, which is correct for a genuinely shared reference (`grid`,
# `cruise`) but would silently keep ONE dataset's `obs` and drop the other 14.
# So the core is excluded here and assembled by union below (assemble_core()).
core_shard_tables <- c(
"sample", "obs", "obs_attribute", "sample_measurement", "obs_ctd_full", "obs_mets_full",
"taxon", "dataset_taxon", "taxon_group")
# use only canonical, non-supplemental tables
reg_canon <- registry |>
filter(canonical, !supplemental, !table %in% core_shard_tables)
message(glue(
"{nrow(reg_canon)} canonical tables from ",
"{length(unique(reg_canon$ingest))} ingests"))
# --- authoritative dataset metadata + ERD coloring from ingest YAML ----
# table -> provider_dataset(s) owned, from each ingest's calcofi.tables_owned
ingest_yaml <- read_ingest_yaml(here(), in_release_only = TRUE)
table_dataset <- list()
add_owner <- function(tbl, pd) {
if (is.null(tbl)) return(invisible())
table_dataset[[tbl]] <<- unique(c(table_dataset[[tbl]], pd))
}
for (key in names(ingest_yaml)) {
cc <- ingest_yaml[[key]]
for (e in cc$tables_owned %||% list()) add_owner(e$table, key)
for (ad in cc$additional_datasets %||% list()) {
pd2 <- paste0(ad$provider, "_", ad$dataset)
for (e in ad$tables_owned %||% list()) add_owner(e$table, pd2)
}
}
# one color per dataset (from calcofi.erd.color)
dataset_colors <- lapply(ingest_yaml, function(cc) cc$erd$color)
# release-level config: neutral ERD overrides for common tables
rel_cfg <- read_calcofi_meta(here("release_database.qmd"))
release_overrides <- rel_cfg$erd_overrides
# cross-dataset foreign keys (relationships spanning ingests) are authored in a
# reviewable CSV; intra-dataset FKs live in each ingest's relationships.json.
cross_fks_df <- readr::read_csv(
here("metadata/relationships_cross.csv"), show_col_types = FALSE)
cross_fks <- lapply(seq_len(nrow(cross_fks_df)), function(i)
as.list(cross_fks_df[i, c("table", "column", "ref_table", "ref_column")]))
# stroke-based color map consumed by every cc_erd() call below
color_map <- cc_erd_color_map(
table_dataset = table_dataset,
dataset_colors = dataset_colors,
overrides = release_overrides,
neutral = "#dcdcdc")
# create VIEWs on local parquet for each canonical table
# _new delta tables handled separately for merging
#
# A table carrying geometry MUST be listed here, and the cost of omitting it is
# silent: `load_prior_tables()` only converts the parquet's WKB BLOB back to
# GEOMETRY for the tables named, so an omitted one arrives as a BLOB, the CRS
# normalization below (which selects on `data_type LIKE 'GEOMETRY%'`) never sees
# it, it never joins `crs_local_tables`, and it is therefore GCS-copied straight
# from the ingest bucket with whatever tag the ingest happened to mint. Nothing
# fails; a consumer's ST_Intersects against `sample.geom` does, later.
# `region` gained a POLYGON when the phytoplankton pooling regions stopped being
# provisional centroids (workflows#76).
all_geom_tables <- c("grid", "site", "segment", "casts", "ctd_cast", "spatial",
"region")
main_tables <- reg_canon |> filter(!grepl("_new$", table))
new_tables <- registry |> filter(grepl("_new$", table))
load_stats <- purrr::map_dfr(
split(main_tables, seq_len(nrow(main_tables))),
function(row) {
load_prior_tables(
con = con_wdl,
parquet_dir = row$parquet_dir,
tables = row$table,
geom_tables = all_geom_tables,
as_view = TRUE
)
})
# merge {table}_new additions into their base tables
# driven by calcofi.modifies in YAML frontmatter
if (nrow(new_tables) > 0) {
# group _new tables by their base table
base_names <- unique(sub("_new$", "", new_tables$table))
for (base_tbl in base_names) {
delta_rows <- new_tables |> filter(table == paste0(base_tbl, "_new"))
# replace VIEW with TABLE for this base table (so we can INSERT)
base_src <- main_tables |> filter(table == base_tbl)
if (nrow(base_src) > 0) {
dbExecute(con_wdl, glue("DROP VIEW IF EXISTS {base_tbl}"))
load_prior_tables(
con = con_wdl, parquet_dir = base_src$parquet_dir[1],
tables = base_tbl, geom_tables = all_geom_tables)
# get PK column for dedup
pk_col <- dbGetQuery(con_wdl, glue(
"SELECT column_name FROM information_schema.columns
WHERE table_name = '{base_tbl}'
ORDER BY ordinal_position LIMIT 1"))$column_name
for (j in seq_len(nrow(delta_rows))) {
dr <- delta_rows[j, ]
pq_path <- file.path(dr$parquet_dir, paste0(base_tbl, "_new.parquet"))
if (file.exists(pq_path)) {
dbExecute(con_wdl, glue(
"INSERT INTO {base_tbl}
SELECT * FROM read_parquet('{pq_path}')
WHERE {pk_col} NOT IN (SELECT {pk_col} FROM {base_tbl})"))
n_new <- dbGetQuery(con_wdl, glue(
"SELECT COUNT(*) AS n FROM read_parquet('{pq_path}')"))$n
message(glue("Merged {n_new} {base_tbl} addition(s) from {dr$ingest}"))
}
}
}
}
}
load_stats |>
datatable(caption = "Assembled tables (VIEWs on local parquet)")
```
## Dataset Reference
The `dataset` reference table, keyed by `dataset_key = provider_dataset`.
The Phase-1 `v_obs_env` / `v_obs_bio` / `v_obs` VIEWs that used to be built here
are gone. They projected each dataset's per-dataset measurement tables into a
common shape to prove the consolidation target non-destructively, *without*
re-running the ingests. That job is done: every ingest now emits its slice of
`obs` directly, so the views' source tables (`bottle_measurement`, `casts`,
`ctd_measurement`, …) no longer exist and the real `obs` table assembled below
supersedes them. They were release-local — nothing outside this notebook read
them.
```{r}
#| label: dataset_ref
# dataset reference: dataset_key = provider_dataset, built from the ingest YAML
# rather than metadata/dataset.csv. The YAML is authoritative (it deprecates the
# CSV) and, more to the point, it cannot go stale: it is derived from the same
# `calcofi:` blocks that define the pipeline, so every ingest is present by
# construction. The CSV had drifted — it was missing calcofi_mets,
# cce-lter_picoplankton-bacteria and sio_mesopelagic-fish, which orphaned
# 533,571 obs rows against the obs.dataset_key foreign key.
d_dataset <- ingest_yaml_to_dataset_df(ingest_yaml) |>
mutate(dataset_key = paste0(provider, "_", dataset), .before = 1)
dbExecute(con_wdl, "DROP VIEW IF EXISTS dataset")
dbWriteTable(con_wdl, "dataset", as.data.frame(d_dataset), overwrite = TRUE)
dbGetQuery(con_wdl, "SELECT dataset_key, dataset_name FROM dataset ORDER BY 1") |>
datatable(caption = "dataset reference")
```
## Consolidated Core Tables
The **core** tables every consumer reads, replacing the ~40 per-dataset triples:
keyed by a namespaced `sample_key` (`dataset_key:sample_type:id`) and stamped
with a computed H3 `hex_id`. See `design_env-bio-consolidation.md`.
This step **concatenates, it does not derive.** Each ingest projects itself into
the core in its own notebook ("Emit Core Tables") — the single authoritative
projection, owned by the notebook that owns the dataset — and writes its slice as
parquet. `assemble_core()` unions those
shards, renumbers the surrogate ids globally (every ingest numbers from 1 within
its own shard) and merges the `taxon` slices by source priority. Deriving the
core here as well is what let the two projections drift apart, so that
duplication is gone.
```{r}
#| label: core_tables
# measurement_type: authoritative from the metadata CSV (adds abundance, count,
# body_length, and the event-level effort types), replacing any per-ingest VIEW
# so the FK parity check below sees the current vocabulary.
dbExecute(con_wdl, "DROP VIEW IF EXISTS measurement_type")
# Read the registry through calcofi4db::read_measurement_type() rather than
# DuckDB's read_csv_auto. This used to be a direct read_csv_auto, and that is how
# the release shipped literal "NA" strings: an ingest wrote the registry with
# readr's default `na = "NA"`, which is invisible to read_csv() but NOT to
# read_csv_auto, whose default nullstr is the empty string only. 161 rows of
# `_qual_column` and 192 of `_prec_column` were affected, plus `is_canonical`.
# The helper reads strictly (na = "") and ERRORS on sentinel strings, so a
# corrupted registry now fails the release instead of being published by it.
d_meas_type_reg <- read_measurement_type(here("metadata/measurement_type.csv"))
dbWriteTable(con_wdl, "_measurement_type_reg", as.data.frame(d_meas_type_reg),
overwrite = TRUE)
# derive provider/dataset from _source_datasets (first source) so the schema site
# + query app ("browse measurement types") keep their provider/dataset columns.
dbExecute(con_wdl,
"CREATE OR REPLACE TABLE measurement_type AS
SELECT *,
split_part(split_part(_source_datasets, ';', 1), '_', 1) AS provider,
regexp_replace(split_part(_source_datasets, ';', 1), '^[^_]*_', '') AS dataset
FROM _measurement_type_reg")
dbExecute(con_wdl, "DROP TABLE _measurement_type_reg")
# --- assemble the core from the per-dataset shards --------------------------
# Each ingest emits its own slice from its own notebook, which is the single
# authoritative projection (calcofi4db holds only the generic shapes). This step only concatenates: it UNIONs the
# shards, renumbers the surrogate ids globally (each ingest numbers from 1 within
# its own shard), merges the `taxon` slices with source priority, and asserts
# `sample_key` is globally unique. Nothing is re-derived here — that duplication
# is exactly what let the release and the ingests drift apart.
# Supplemental full-resolution tables are DISCOVERED from the ingests' YAML, not
# hardcoded — obs_ctd_full was the only one until calcofi_mets added obs_mets_full,
# and a hardcoded name silently drops a new one from the release while the ingest
# keeps writing it. BUILD_OBS_CTD_FULL=FALSE still skips them all for a fast run.
build_supplemental <- as.logical(Sys.getenv("BUILD_OBS_CTD_FULL", "TRUE"))
supp_tbls <- supplemental_core_tables(here(), build_supplemental)
if (length(supp_tbls))
message(glue("supplemental tables: {paste(supp_tbls, collapse = ', ')}"))
core_n <- assemble_core(con_wdl, root = here(), supplemental = supp_tbls)
# Vernacular names, applied ONCE to the merged `taxon` rather than in each of the
# 10 taxa-emitting ingests. `common_name` only ever came from a dataset's own
# vocabulary, so every taxon resolved through measurement_taxon.csv /
# taxon_override.csv arrived with none — 57% of them at v2026.08.14, including
# worms:440388 Metacarcinus magister, whose missing "Dungeness crab" in
# db-viz-hex surfaced this.
#
# Central for the same reason `dataset` and the observed coverage columns are:
# the shards are MERGED here, not rebuilt, so one application cannot drift across
# ten of them. A dataset's own common name always wins — it is what the provider
# publishes. A taxon whose WoRMS vernaculars are ambiguous stays NULL until a
# human picks one in the registry; see metadata/taxon_common.csv.
n_common <- apply_taxon_common(con_wdl, here("metadata/taxon_common.csv"))
tibble(
table = names(core_n),
rows = unlist(core_n)) |>
datatable(caption = "Core tables assembled from per-dataset ingest shards")
```
```{r}
#| label: core_by_dataset
dbGetQuery(con_wdl,
"SELECT dataset_key, count(*) n_obs, count(DISTINCT sample_key) n_samples,
count(DISTINCT hex_id) n_hex
FROM obs GROUP BY 1 ORDER BY 1") |>
datatable(caption = "obs: consolidated observations by dataset")
```
### Observed Coverage
Each dataset's temporal and spatial extent, **measured from the assembled core
rather than asserted**. These overwrite the `dataset` table's
`coverage_temporal` / `coverage_spatial`, which used to carry a hand-written
string from each ingest's `calcofi.dataset_meta` YAML.
Those strings could not help going stale — authored once, with the data growing
underneath them. At `v2026.08.06` seven of fifteen were wrong: `cce-lter_zoodb`
claimed coverage through 2021-05 when its data ends 2015-04, `calcofi_phyllosoma`
stopped a year short of its own rows, and three said "present" while in fact
stalling in 2019, 2022 and 2023. The YAML keys are now gone; the only ones left
are where the data genuinely cannot answer (see `coverage_fallback` below), and
each carries a comment saying so.
```{r}
#| label: dataset_coverage
# measured, not asserted. observed_coverage() filters coordinates with
# isfinite() rather than IS NOT NULL: NaN survives a nullity test and min()/max()
# propagate it, so one poisoned row would blow a dataset's whole bbox out to NaN
# with every check still passing.
d_cov <- observed_coverage(con_wdl)
# fall back to a declared static value ONLY where the data cannot answer.
# calcofi_phytoplankton is region-pooled: it carries real coordinates but no
# datetime at all, so it measures spatially and not temporally. Held-out
# datasets (in_release: false) never reach the core, so they never appear here.
d_dataset_cov <- d_dataset |>
left_join(d_cov, by = "dataset_key") |>
mutate(
coverage_temporal = coalesce(coverage_temporal_observed, coverage_temporal),
coverage_spatial = coalesce(coverage_spatial_observed, coverage_spatial)) |>
select(all_of(names(d_dataset)))
# `dataset` is written as a TABLE at [dataset_table] above, so the drop has to
# match that type. DuckDB's `DROP VIEW IF EXISTS` does NOT no-op on a type
# mismatch — it raises "Existing object dataset is of type Table, trying to drop
# type View" — so the unconditional DROP VIEW here failed every release run.
# Ask the catalog rather than assume, since a compat VIEW of the same name is a
# legitimate state for this connection to be in.
ds_type <- dbGetQuery(con_wdl, "
SELECT table_type FROM information_schema.tables
WHERE table_name = 'dataset'")$table_type
if (length(ds_type))
dbExecute(con_wdl, if (identical(ds_type[1], "VIEW"))
"DROP VIEW IF EXISTS dataset" else "DROP TABLE IF EXISTS dataset")
dbWriteTable(con_wdl, "dataset", as.data.frame(d_dataset_cov), overwrite = TRUE)
# report which half of which dataset fell back, so a silent gap cannot hide as a
# confidently-rendered string on the schema site
coverage_fallback <- d_dataset |>
left_join(d_cov, by = "dataset_key") |>
filter(is.na(coverage_temporal_observed) | is.na(coverage_spatial_observed)) |>
transmute(dataset_key,
temporal = if_else(is.na(coverage_temporal_observed),
paste("asserted:", coverage_temporal), "measured"),
spatial = if_else(is.na(coverage_spatial_observed),
paste("asserted:", coverage_spatial), "measured"))
cat(glue(
"coverage measured for {sum(!is.na(d_cov$coverage_temporal_observed))} datasets ",
"temporally, {sum(!is.na(d_cov$coverage_spatial_observed))} spatially; ",
"{nrow(coverage_fallback)} fell back to an asserted value\n"))
d_cov |>
select(dataset_key, coverage_temporal_observed, coverage_spatial_observed) |>
datatable(caption = "observed coverage, measured from obs + sample")
```
### Core Table Parity Checks
Hard assertions on the assembled core. The old checks compared it against the
per-dataset tables (`net`, `casts`, `ctd_cast`, …), which the ingests no longer
publish — and which was only meaningful while the core was re-derived here.
Now that each ingest emits its own slice, the checks that matter are
**conservation** (no shard silently dropped by the union), **global key
uniqueness** after renumbering, and **referential integrity**. A break fails the
render. See `design_env-bio-consolidation.md` Verification.
```{r}
#| label: core_parity
q <- function(sql) dbGetQuery(con_wdl, sql)$n
# (A) shard conservation — the assembled core must contain exactly the rows the
# ingests emitted. This replaces the old per-dataset assertions (which compared
# against `net`/`casts`/`ctd_cast`, tables the ingests no longer publish) and is
# a stronger check: it catches a shard silently dropped by the union, which the
# canonical-first registry would otherwise do without complaint.
shard_total <- function(tbl) {
paths <- core_shard_paths(tbl, root = here())
if (!length(paths)) return(0)
sum(vapply(paths, function(p) {
rd <- if (grepl("\\*\\*", p))
glue("read_parquet('{p}', hive_partitioning = true, union_by_name = true)") else
glue("read_parquet('{p}', union_by_name = true)")
as.numeric(dbGetQuery(con_wdl, glue("SELECT COUNT(*) AS n FROM {rd}"))$n)
}, numeric(1)))
}
core_tbls <- intersect(
c("sample", "obs", "obs_attribute", "sample_measurement"), dbListTables(con_wdl))
conservation <- tibble(
table = core_tbls,
shards = vapply(core_tbls, shard_total, numeric(1)),
assembled = vapply(core_tbls, function(t)
as.numeric(q(glue("SELECT COUNT(*) AS n FROM {t}"))), numeric(1))) |>
mutate(ok = shards == assembled)
print(as.data.frame(conservation))
stopifnot("every ingest shard must survive the union" = all(conservation$ok))
# (B) surrogate ids must be globally unique after renumbering ----------------
id_dups <- c(
"obs.obs_id" = q("SELECT COUNT(*) n FROM (SELECT obs_id FROM obs GROUP BY 1 HAVING COUNT(*) > 1)"),
"obs_attribute.obs_attribute_id" = if ("obs_attribute" %in% dbListTables(con_wdl))
q("SELECT COUNT(*) n FROM (SELECT obs_attribute_id FROM obs_attribute GROUP BY 1 HAVING COUNT(*) > 1)") else 0,
"sample.sample_key" = q("SELECT COUNT(*) n FROM (SELECT sample_key FROM sample GROUP BY 1 HAVING COUNT(*) > 1)"))
if (any(id_dups > 0)) print(id_dups[id_dups > 0])
stopifnot("core surrogate keys must be globally unique" = all(id_dups == 0))
# (C) FK validity — every core row resolves against its reference, INCLUDING the
# unified taxon (obs/obs_attribute/dataset_taxon all key into taxon.taxon_key) ---
fk_bad <- c(
"obs.dataset_key" = q("SELECT COUNT(*) n FROM obs WHERE dataset_key NOT IN (SELECT dataset_key FROM dataset)"),
"obs.sample_key" = q("SELECT COUNT(*) n FROM obs WHERE sample_key NOT IN (SELECT sample_key FROM sample)"),
"obs.grid_key" = q("SELECT COUNT(*) n FROM obs WHERE grid_key IS NOT NULL AND grid_key NOT IN (SELECT grid_key FROM grid)"),
"obs.measurement_type" = q("SELECT COUNT(*) n FROM obs WHERE measurement_type NOT IN (SELECT measurement_type FROM measurement_type)"),
"obs.taxon_key" = q("SELECT COUNT(*) n FROM obs WHERE taxon_key IS NOT NULL AND taxon_key NOT IN (SELECT taxon_key FROM taxon)"),
"sample.parent_sample_key" = q("SELECT COUNT(*) n FROM sample WHERE parent_sample_key IS NOT NULL AND parent_sample_key NOT IN (SELECT sample_key FROM sample)"),
"obs_attribute.sample_key" = if ("obs_attribute" %in% dbListTables(con_wdl))
q("SELECT COUNT(*) n FROM obs_attribute WHERE sample_key NOT IN (SELECT sample_key FROM sample)") else 0,
"obs_attribute.taxon_key" = if ("obs_attribute" %in% dbListTables(con_wdl))
q("SELECT COUNT(*) n FROM obs_attribute WHERE taxon_key IS NOT NULL AND taxon_key NOT IN (SELECT taxon_key FROM taxon)") else 0,
"dataset_taxon.taxon_key" = q("SELECT COUNT(*) n FROM dataset_taxon WHERE taxon_key NOT IN (SELECT taxon_key FROM taxon)"),
"sample_measurement.sample_key" = q("SELECT COUNT(*) n FROM sample_measurement WHERE sample_key NOT IN (SELECT sample_key FROM sample)"),
# the measurement vocabulary must cover EVERY grain, not just obs: promoting
# bottom_depth_m into sample_measurement added a type that was not registered,
# and with only obs.measurement_type asserted it went unnoticed.
"sample_measurement.measurement_type" = q("SELECT COUNT(*) n FROM sample_measurement WHERE measurement_type NOT IN (SELECT measurement_type FROM measurement_type)"),
"obs_attribute.measurement_type" = if ("obs_attribute" %in% dbListTables(con_wdl))
q("SELECT COUNT(*) n FROM obs_attribute WHERE measurement_type NOT IN (SELECT measurement_type FROM measurement_type)") else 0)
if (any(fk_bad > 0)) print(fk_bad[fk_bad > 0])
stopifnot("core FK validity" = all(fk_bad == 0))
# (D) the DIC -> bottle dedup: DIC observations sharing a physical Niskin must
# point at the bottle's event, not mint a second one
n_dic_shared <- q("SELECT COUNT(*) n FROM obs
WHERE dataset_key = 'calcofi_dic'
AND sample_key LIKE 'calcofi_bottle:bottle:%'")
message(glue("DIC observations sharing a bottle event: {format(n_dic_shared, big.mark = ',')}"))
# (E) obs_attribute vs its headline — reported (sources are not always internally
# consistent, so this is a signal, not an assertion)
if ("obs_attribute" %in% dbListTables(con_wdl)) {
attr_check <- dbGetQuery(con_wdl, "
WITH f AS (SELECT sample_key, taxon_key, life_stage, SUM(count) s FROM obs_attribute
WHERE measurement_type='stage' GROUP BY 1,2,3),
o AS (SELECT sample_key, taxon_key, life_stage, SUM(measurement_value) a FROM obs
WHERE measurement_type='abundance' GROUP BY 1,2,3)
SELECT count(*) n_occ, count(*) FILTER (WHERE f.s > o.a) n_stage_gt_headline
FROM f JOIN o USING (sample_key, taxon_key, life_stage)")
message(glue("obs_attribute stage vs abundance: {attr_check$n_stage_gt_headline}/{attr_check$n_occ} occurrences exceed headline (source quirk)"))
}
message("Core parity checks passed.")
```
### Taxon Authority Coverage
A taxon that reaches the release without an authority id is invisible to any
consumer that filters or joins on one, and until v2026.08.05 nothing said so:
all 128 Farallon taxa and 64,956 observations were unreachable through
`db-viz-hex::get_sp()`'s `worms_id` join while every check here passed.
`check_taxon_ids()` **fails the release** on a dataset-local `taxon_key` that is
not declared below. The allowlist is deliberately one key at a time — these are
non-taxonomic operational classes the source records as data, not lookup
failures — so a *new* unresolved taxon can never hide among the known ones.
```{r}
#| label: taxon_authority_coverage
# non-taxonomic classes: real categories in the source that no authority can key.
# Anything NOT on this list that resolves to a dataset-local key fails the render.
TAXON_LOCAL_ALLOW <- c(
# ZooScan operational classes (Q03 in cce-lter/zooscan/questions.csv)
"cce-lter_zooscan:13", # eggs
"cce-lter_zooscan:15", # multiples (several organisms in one vignette)
"cce-lter_zooscan:16", # nauplii (crustacean naupliar stage, not a taxon)
"cce-lter_zooscan:18", # others
# phytoplankton: two different things, kept apart on purpose (Q05 in
# calcofi/phytoplankton/questions.csv). Nine codes are absent from the source
# Definitions sheet altogether, so there is no name to resolve; 232 is present
# and named (*Danasphaera indica*) but has no WoRMS record, fuzzy included.
#
# This list was 14 and is now 10. The other four (40, 231, 337, 597) were
# never unnameable — they carry real names in the Definitions sheet and only
# fell through because their `taxa` is "other", which no functional-group
# override row matches. They now resolve to accepted genera via
# `species_code` rows in metadata/taxon_override.csv. An allowlist is for taxa
# no authority CAN key, not for ones our own join missed.
paste0("calcofi_phytoplankton:",
c("4", "59", "218", "229", "232", "300", "454", "532", "540", "596")))
tx_cover <- check_taxon_ids(con_wdl, allow = TAXON_LOCAL_ALLOW, halt = TRUE)
tx_cover |>
datatable(caption = paste(
"Taxon authority coverage by dataset.",
"`n_local_key` counts taxa no authority resolved (all allowlisted, or this",
"chunk would have failed); `n_no_worms` is reported, not gated — WoRMS",
"legitimately lacks a few taxa, and an itis:-keyed bird is correctly keyed",
"either way. `n_no_rank_order` should be 0: it was every ITIS-keyed taxon",
"until the rank vocabulary moved out of a single ingest's connection into",
"calcofi4db::taxa_rank_reference()."))
```
## Declared Measurement Bounds
The backstop for the per-dataset bounds check that each ingest runs (see
`check_measurement_bounds()` in every `ingest_*.qmd`). The ingest is where a
finding is *actionable* — the source is open, the provider can be asked, and a
question lands in `questions.csv`. This chunk exists so that a notebook which
skipped the check, or a `measurement_type.csv` bound edited after an ingest last
ran, cannot ship an impossible value to consumers.
The two halves are gated differently, on purpose:
* **`out_of_range` fails the release.** A bound was agreed and the data breaks it.
There is no reading of that which should reach a consumer.
* **`undeclared` is reported, not gated.** 73 of 98 (dataset, type) pairs and 67%
of `obs` rows had no bound at v2026.08.07, so gating on it would block every
release rather than fix anything. `BOUNDS_UNDECLARED_MAX` ratchets: it is the
count on the day this landed, and it may only ever go **down**. A new
undeclared type therefore fails the release even though the backlog does not.
```{r}
#| label: bounds_coverage
# ratchet, not a target. Lower it whenever bounds are declared; never raise it.
# Raising it to make a release pass is how the backlog became 73 in the first
# place — take the finding to the ingest and declare the bound there.
#
# 73 -> 30 for `obs` at v2026.08.08: every type whose live values already
# satisfied a defensible bound got one, reusing the vocabulary the registry had
# already agreed for the same quantity under its other name (btl_temperature
# -2..40, salinity_* 0..45, oxygen umol/kg 0..700, ...). What remains is where
# the defensible bound is VIOLATED by published data — i.e. the findings — each
# a `proposed` question in its dataset's questions.csv. Declaring those before
# the provider answers would delete real observations.
#
# The count covers `obs` AND the supplemental tables from v2026.08.08, so it
# jumped when they were first checked rather than because anything regressed.
# Set from the measured value on the day; it may only ever go DOWN.
BOUNDS_UNDECLARED_MAX <- 77L
d_bounds <- purrr::map_dfr(
dbGetQuery(con_wdl, "SELECT DISTINCT dataset_key FROM obs ORDER BY 1")$dataset_key,
\(dk) check_measurement_bounds(con_wdl, "obs", dataset_key = dk) |>
mutate(table = "obs", dataset_key = dk, .before = 1))
# The SUPPLEMENTAL tables are published and were not checked here until
# v2026.08.08. That gap was not theoretical: v2026.08.07's `obs_ctd_full` shipped
# 5,963 `ph` values below the declared floor (to -2.98) that the CTD ingest had
# already removed from its own output — the released bytes did not match the
# staged ones, and every check in this notebook looked only at `obs`, so nothing
# anywhere disagreed. Checking `obs` alone certifies a third of the release.
#
# Cost is not a reason to skip them: 216M rows of obs_ctd_full check in ~20s,
# because the work is a GROUP BY per type over a column DuckDB reads lazily.
d_bounds <- bind_rows(d_bounds, purrr::map_dfr(
intersect(supp_tbls, dbListTables(con_wdl)),
\(tb) check_measurement_bounds(con_wdl, tb) |>
mutate(table = tb, dataset_key = paste0("(supplemental) ", tb), .before = 1)))
n_oob <- sum(d_bounds$status == "out_of_range")
n_und <- sum(d_bounds$status == "undeclared")
cat(glue("bounds: {n_oob} out-of-range type(s), {n_und} undeclared ",
"(ratchet {BOUNDS_UNDECLARED_MAX}), ",
"{sum(d_bounds$status == 'ok')} ok, across ",
"{n_distinct(d_bounds$table)} table(s) and ",
"{format(sum(d_bounds$n_total), big.mark = ',')} values\n"))
d_bounds |>
filter(status != "ok") |>
select(table, dataset_key, measurement_type, status, n_total, n_bad, pct_bad,
v_min, v_max, valid_min, valid_max) |>
datatable(caption = paste(
"Measured values against metadata/measurement_type.csv, across `obs` AND the",
"supplemental full-resolution tables.",
"`out_of_range` fails this render; `undeclared` is the coverage backlog —",
"nothing was checked for those types, so their absence from the",
"out_of_range list means nothing."))
# `stopifnot` rather than a warning: a warning here is indistinguishable from the
# ~40 benign ones a full release render emits, which is how the CTD values shipped
stopifnot(
"values outside declared valid_min/valid_max — fix at the ingest, not here" =
n_oob == 0,
"a measurement type lost its bounds; declare it in the owning ingest" =
n_und <= BOUNDS_UNDECLARED_MAX)
if (n_und < BOUNDS_UNDECLARED_MAX)
cat(glue("\nBOUNDS_UNDECLARED_MAX can be tightened to {n_und}.\n"))
```
## Cruise Coverage — Samples With No Observations
The one shape of loss that every other check here is blind to, by construction.
PK/FK validation runs **child → parent**: it asks whether each `obs` row has a
parent in `sample`. A cruise whose observations vanish entirely leaves its casts
behind as parents with no children, which violates nothing. The bounds check above
inspects `obs`, which such a cruise has left. So `v2026.08.08` published 10
`calcofi_ctd-cast` cruises holding all 1,186 of their casts and none of their
874,000 observations, and every check in this notebook passed.
The grain is the **cruise**, not the sample: a CTD `sample` row is one physical
cast *per direction* while `obs` keeps one direction, so ~half of that dataset's
cast rows legitimately carry no observations. A dataset that emits no observations
at all is exempt — `sio_pic-zooplankton` is a net-tow registry whose biovolumes are
pending from the provider, so its 587 `sample`-only cruises are its designed state,
not 587 failures.
`ORPHAN_CRUISES_MAX` ratchets exactly like `BOUNDS_UNDECLARED_MAX`: it is the
per-dataset backlog measured on the day this landed, and it may only ever go
**down**. `calcofi_ctd-cast` is deliberately **not** in it — its correct value is
zero and the ingest now asserts that, so a release cut before the CTD ingest is
re-run fails here rather than republishing the loss.
```{r}
#| label: cruise_coverage
# ratchet, not a target. Each of these is an open question about a dataset that
# has cruises with no observations; none has been shown to be legitimate. Lower
# an entry whenever one is resolved at its ingest; never raise one.
ORPHAN_CRUISES_MAX <- c(
# every orphan is a position-less or mis-positioned event whose measurements
# exist but are held out of `obs` by the `grid_key IS NOT NULL` filter in each
# ingest's core projection. Investigated 2026-08-10; the causes differ:
# cce-lter_zoodb 156 tows with NULL datetime/latitude/grid_key
# swfsc_ichthyo 15 cruises have no tows in the source at all (nothing
# lost); the other 5 hold 1,977 ichthyo rows behind
# ungridded sites AND a NULL measurement_type
# calcofi_mets 1207OS publishes no lat/lon (mets_16, answered "skip the
# spatial join") — ungridded by design, not by defect. Was 5
# until the Longitude_W sign repair landed the other four.
# swfsc_cufes 1,475 samples with ZERO rows in cufes_measurement
# cce-lter_euph. 4 tows with ZERO rows in euphausiids_measurement
# The last two are not losses: the provider recorded the event and no counts.
# cdfw_dungeness-crab is deliberately ABSENT: its 14 orphan cruises are an
# inventory grain, not a loss, and that is expressed by EFFORT_ONLY_TYPES below
# rather than by an allowance. An allowance of 14 would also hide the next 14
# real losses in that dataset; the exemption hides none, because its observing
# sample types stay held to zero.
"cce-lter_zoodb" = 41L,
"swfsc_ichthyo" = 20L,
"swfsc_cufes" = 3L,
"calcofi_mets" = 1L,
"cce-lter_euphausiids" = 1L)
# NOT `d_cov` — that name is live from the `dataset_coverage` chunk above and is
# read again in `upload_frozen` (d_cov$coverage_temporal_observed). Reusing it
# here silently replaced that data frame and killed a 50-minute release run at
# the very last chunk, after the freeze and most of the upload had completed.
# Sample types that record EFFORT or INVENTORY rather than an analyzed event, so
# a cruise made only of them is not a finding. cdfw_dungeness-crab's 2,011 `tow`
# rows are a 60-year sorting log of which archived jars exist — only 216 were
# ever examined — while its 310 `subsample` rows are the lab-examined aliquots
# and every one yields obs. Keyed by dataset because `tow` IS an observing type
# for the net-tow ingests.
EFFORT_ONLY_TYPES <- c("cdfw_dungeness-crab" = "tow")
d_cruise_cov <- check_cruise_coverage(
con_wdl, max_orphan_cruises = ORPHAN_CRUISES_MAX,
effort_only_types = EFFORT_ONLY_TYPES)
d_cruise_cov |>
datatable(caption = paste(
"Cruises carrying samples with no observations, per dataset.",
"`emits_obs = FALSE` marks a registry-only dataset, exempt by design.",
"Anything above its ratchet fails this render."))
tighten <- d_cruise_cov$dataset_key[
d_cruise_cov$dataset_key %in% names(ORPHAN_CRUISES_MAX) &
d_cruise_cov$cruises_no_obs < ORPHAN_CRUISES_MAX[d_cruise_cov$dataset_key]]
if (length(tighten))
cat(glue(
"ORPHAN_CRUISES_MAX can be tightened: ",
"{paste(sprintf('%s -> %d', tighten,
d_cruise_cov$cruises_no_obs[match(tighten, d_cruise_cov$dataset_key)]),
collapse = ', ')}\n"))
```
## Ungridded Observations — Released, and Asked About
From v2026.08.11 `obs` carries observations that resolve no CalCOFI grid cell.
Every ingest used to filter `WHERE grid_key IS NOT NULL` in its core projection
while the `sample` arm did not, so an off-grid event kept its sample row and lost
every observation under it — which is how four `calcofi_mets` cruises reached
v2026.08.08 as 11,762 underway samples with zero observations.
The exclusion also contradicted this pipeline's own reasoning: `obs_mets_full`
was already gated on *a position* rather than on `grid_key` because "a ship on
transit is legitimately outside the CalCOFI station grid", and
`calcofi_phytoplankton` is region-pooled and has emitted ungridded `obs` from the
start.
Not dropping them puts the burden here instead: an ungridded observation is an
off-grid position, a coarser spatial notion, or **a coordinate error**, and
nothing in the pipeline can tell those apart. The sign-flipped `Longitude_W` that
put five CalCOFI cruises in the Taiwan Strait was invisible precisely *because*
being off-grid removed the rows silently. So this reports rather than gates, and
each dataset with a non-zero share owes a `questions.csv` entry — the `finding`
column is written to be pasted straight into one.
```{r}
#| label: ungridded_obs
d_ungridded <- check_ungridded_obs(con_wdl)
d_ungridded |>
select(dataset_key, n_obs, n_ungridded, pct_ungridded, n_no_position) |>
datatable(caption = paste(
"Observations resolving no CalCOFI grid cell, per dataset.",
"`n_no_position` is the subset carrying no latitude/longitude at all —",
"the distinction a provider needs in order to answer.")) |>
formatCurrency(c("n_obs", "n_ungridded", "n_no_position"),
currency = "", digits = 0, mark = ",")
d_ungridded |>
filter(!is.na(finding)) |>
select(dataset_key, finding) |>
datatable(caption = paste(
"Paste each finding into that dataset's questions.csv as `context`,",
"with status `open` until the provider says which of the three it is."))
```
## Scan Manifests for Mismatches
```{r}
#| label: scan_mismatches
# scan all ingest manifests for unresolved mismatches
all_manifests <- in_release_dirs(list.files(
"data/parquet", "manifest.json",
recursive = TRUE, full.names = TRUE))
all_mismatches <- purrr::compact(lapply(all_manifests, function(mf) {
m <- jsonlite::read_json(mf)
if (is.null(m$mismatches)) return(NULL)
dataset <- basename(dirname(mf))
purrr::imap_dfr(m$mismatches, function(items, category) {
if (length(items) == 0) return(NULL)
purrr::map_dfr(items, function(x) {
# replace NULL values with NA so as_tibble works
x[vapply(x, is.null, logical(1))] <- NA
as_tibble(x)
}) |>
mutate(dataset = dataset, category = category, .before = 1)
})
}))
if (length(all_mismatches) > 0) {
d_mismatches <- bind_rows(all_mismatches)
message(glue("{nrow(d_mismatches)} unresolved mismatch(es) across manifests"))
d_mismatches |>
datatable(caption = "Unresolved mismatches (from manifest.json)")
} else {
message("No unresolved mismatches found across manifests")
}
```
## Validate
Cross-dataset validation to ensure data integrity before freezing.
```{r}
#| label: validate
# grid_key integrity: casts.grid_key should all be in grid.grid_key
tbls <- DBI::dbListTables(con_wdl)
if (all(c("casts", "grid") %in% tbls)) {
# use information_schema to check columns (avoids GEOMETRY type issues)
casts_cols_wdl <- dbGetQuery(
con_wdl,
"SELECT column_name FROM information_schema.columns
WHERE table_name = 'casts'"
)$column_name
grid_cols_wdl <- dbGetQuery(
con_wdl,
"SELECT column_name FROM information_schema.columns
WHERE table_name = 'grid'"
)$column_name
if ("grid_key" %in% casts_cols_wdl && "grid_key" %in% grid_cols_wdl) {
grid_orphans <- dbGetQuery(
con_wdl,
"SELECT COUNT(*) AS n FROM casts c
WHERE c.grid_key IS NOT NULL
AND c.grid_key NOT IN (SELECT grid_key FROM grid)"
)$n
message(glue("Grid key orphans in casts: {grid_orphans}"))
# Grid key orphans in casts: 0
}
}
# ship PK uniqueness
if ("ship" %in% tbls) {
ship_dups <- dbGetQuery(
con_wdl,
"SELECT ship_key, COUNT(*) AS n FROM ship
GROUP BY ship_key HAVING COUNT(*) > 1"
)
if (nrow(ship_dups) > 0) {
warning(glue("Duplicate ship_key values: {nrow(ship_dups)}"))
} else {
message("ship_key: all unique")
}
}
# ship_key: all unique
# cruise PK uniqueness
if ("cruise" %in% tbls) {
cruise_dups <- dbGetQuery(
con_wdl,
"SELECT cruise_key, COUNT(*) AS n FROM cruise
GROUP BY cruise_key HAVING COUNT(*) > 1"
)
if (nrow(cruise_dups) > 0) {
warning(glue("Duplicate cruise_key values: {nrow(cruise_dups)}"))
} else {
message("cruise_key: all unique")
}
}
# cruise_key: all unique
# cruise bridge coverage
if ("casts" %in% tbls) {
bridge_stats <- dbGetQuery(
con_wdl,
"SELECT
COUNT(*) AS total_casts,
SUM(CASE WHEN ship_key IS NOT NULL THEN 1 ELSE 0 END) AS with_ship_key,
SUM(CASE WHEN cruise_key IS NOT NULL THEN 1 ELSE 0 END) AS with_cruise_key
FROM casts"