Skip to content

Implement Event Collection API using Spanner#1811

Open
keyurva wants to merge 4 commits intodatacommonsorg:masterfrom
keyurva:event-collection
Open

Implement Event Collection API using Spanner#1811
keyurva wants to merge 4 commits intodatacommonsorg:masterfrom
keyurva:event-collection

Conversation

@keyurva
Copy link
Contributor

@keyurva keyurva commented Mar 13, 2026

  • Events are fetched from SG based on type, place, and date.
  • Filtering is implemented in memory.
  • Golden tests are truncated to avoid large golden files (affects only unfiltered queries).

Known Discrepancies with V2

  • propVals order: The order of keys in propVals is different from V2.
  • geoJsonCoordinates escaping: In the V2 response, quotes are triple-escaped (\\\"), whereas in the Spanner response they are single-escaped (\").
V2 geoJsonCoordinates
image
V3 geoJsonCoordinates
image

@n-h-diaz - let me know if this can cause issues and I can change the V3 escaping.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces the Event Collection API, enabling the retrieval of event data from Spanner. It achieves feature parity with the existing V2 implementation, allowing users to query events by type, location, and date, with support for additional filtering capabilities.

Highlights

  • Spanner Implementation: Added logic to find events matching type, place, and date using Spanner Graph. Added logic to fetch properties for the found events. Implemented in-memory filtering for events with standard filters (e.g. area). Ensured deterministic event ordering.
  • Data Source Layer: Wired up the Spanner data source to handle event collection requests.
  • Tests: Added unit and integration tests for the new functionality. Generated golden files for verification. Truncated large golden files to improve test execution time.
Changelog
  • internal/server/spanner/client.go
    • Imported the new pbv1 proto package.
    • Added GetEventCollectionDcids and GetEventCollection methods to the SpannerClient interface.
  • internal/server/spanner/datasource.go
    • Imported v2e for event parsing.
    • Added a new conditional block to handle event collection requests by calling handleEventCollection.
    • Implemented parseEventCollection function to extract event collection request parameters from V2 event requests.
    • Implemented handleEventCollection function to process event collection requests using the Spanner client.
  • internal/server/spanner/golden/datasource/event_collection_lbr.json
    • Added a new golden file containing event collection data for Liberia.
  • internal/server/spanner/golden/datasource/event_collection_lbr_filtered.json
    • Added a new golden file containing filtered event collection data for Liberia.
  • internal/server/spanner/golden/datasource_test.go
    • Imported the new pbv1 proto package.
    • Added mock implementations for GetEventCollectionDcids and GetEventCollection in mockSpannerClient.
    • Introduced new test cases for event collection and filtered event collection in TestSpannerEvent.
    • Modified test logic to trim event collection results to 10 events for golden file generation.
  • internal/server/spanner/golden/query/get_event_collection.json
    • Added a new golden file for the GetEventCollection query results.
  • internal/server/spanner/golden/query/get_event_collection_dcids.json
    • Added a new golden file for the GetEventCollectionDcids query results.
  • internal/server/spanner/golden/query/get_event_collection_filtered.json
    • Added a new golden file for filtered GetEventCollection query results.
  • internal/server/spanner/golden/query_builder/get_event_collection_dcids.sql
    • Added a new golden SQL query for get_event_collection_dcids.
  • internal/server/spanner/golden/query_builder_test.go
    • Added TestGetEventCollectionDcidsQuery to test the event collection DCIDs query builder.
  • internal/server/spanner/golden/query_cases_test.go
    • Added eventCollectionDcidsTestCases for testing event DCID retrieval.
    • Added eventCollectionTestCases for testing event collection with and without filters.
  • internal/server/spanner/golden/query_test.go
    • Imported the new pbv1 proto package.
    • Added TestFindEventDcids to test the retrieval of event DCIDs.
    • Added TestGetEventCollection to test the full event collection retrieval and filtering logic.
  • internal/server/spanner/query.go
    • Added new constants for event predicates like predAffectedPlace, predStartDate, etc.
    • Implemented GetEventCollection to retrieve and filter event collections.
    • Added populateProvenanceInfo and parseDomain to handle provenance data.
    • Implemented assembleEventCollection, assembleAndFilterEvent, populateSpecialFields, populateGeoLocation, populatePropVals, cleanUpPropVals, and keepEvent functions for event assembly and filtering.
    • Implemented GetEventCollectionDcids to fetch event DCIDs from Spanner.
  • internal/server/spanner/query_builder.go
    • Added GetEventCollectionDcidsQuery function to construct Spanner statements for retrieving event DCIDs.
  • internal/server/spanner/statements.go
    • Added getEventCollectionDcids SQL statement for fetching event DCIDs.
Activity
  • No human activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the Event Collection API using Spanner, achieving feature parity with the V2 implementation. The changes are well-structured, with a clear separation of concerns for query building, execution, and data processing. The addition of comprehensive tests and golden files is commendable. I've identified a couple of areas for improvement related to deterministic behavior and code clarity, aligning with best practices for robust and maintainable code.

Comment on lines +421 to +437
for k, v := range arc.Filter {
if k == "typeOf" || k == "date" {
continue
}
if len(v) != 1 {
return nil // Invalid filter
}
spec, err := v2e.ParseEventCollectionFilter(k, v[0])
if err != nil {
return nil // Invalid filter format
}
res.FilterProp = spec.Prop
res.FilterLowerLimit = spec.LowerLimit
res.FilterUpperLimit = spec.UpperLimit
res.FilterUnit = spec.Unit
break // V2 supports at most one extra filter
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The iteration over the arc.Filter map is non-deterministic because map iteration order is not guaranteed in Go. While the comment on line 436 mentions that V2 supports at most one extra filter, relying on this assumption can make the code fragile. If a request with multiple extra filters is ever processed, the behavior will be unpredictable as to which filter is applied. To make the implementation more robust and deterministic, I suggest sorting the filter keys before iterating.

 	// Handle standard filters (e.g. area).
	filterKeys := make([]string, 0, len(arc.Filter))
	for k := range arc.Filter {
		filterKeys = append(filterKeys, k)
	}
	sort.Strings(filterKeys)
	for _, k := range filterKeys {
		if k == "typeOf" || k == "date" {
			continue
		}
		v := arc.Filter[k]
		if len(v) != 1 {
			return nil // Invalid filter
		}
		spec, err := v2e.ParseEventCollectionFilter(k, v[0])
		if err != nil {
			return nil // Invalid filter format
		}
		res.FilterProp = spec.Prop
		res.FilterLowerLimit = spec.LowerLimit
		res.FilterUpperLimit = spec.UpperLimit
		res.FilterUnit = spec.Unit
		break // V2 supports at most one extra filter
	}
References
  1. This rule emphasizes ensuring deterministic order when the underlying system (like map iteration or SPARQL query results without ORDER BY) does not guarantee it. Sorting map keys before iteration aligns with this principle to prevent unpredictable behavior.

Comment on lines +399 to +423
func populateGeoLocation(event *pbv1.EventCollection_Event, value string) {
// Note: The startLocation value in Spanner is usually a latLong/ DCID (e.g. latLong/577521_-958960).
// We parse it here for performance to avoid an extra database roundtrip.
//
// TODO(task): Revisit this optimization if we encounter valid startLocation values
// that are NOT latLong/ DCIDs but still need to be resolved to points, or if the
// assumption that dcids always contain coordinates is not true.
if strings.HasPrefix(value, "latLong/") {
parts := strings.Split(strings.TrimPrefix(value, "latLong/"), "_")
if len(parts) == 2 {
lat, err1 := strconv.ParseFloat(parts[0], 64)
lon, err2 := strconv.ParseFloat(parts[1], 64)
if err1 == nil && err2 == nil {
event.GeoLocations = append(event.GeoLocations, &pbv1.EventCollection_GeoLocation{
Geo: &pbv1.EventCollection_GeoLocation_Point_{
Point: &pbv1.EventCollection_GeoLocation_Point{
Latitude: proto.Float64(lat / 100000.0),
Longitude: proto.Float64(lon / 100000.0),
},
},
})
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function uses several magic strings and numbers ("latLong/", "_", 100000.0). These should be defined as constants at the package level to improve readability and maintainability. This makes it clear what these values represent and makes them easier to change if needed. Since I can only suggest changes within the function, I'll add the scaling factor as a local constant.

func populateGeoLocation(event *pbv1.EventCollection_Event, value string) {
	const latLonScalingFactor = 100000.0
	// Note: The startLocation value in Spanner is usually a latLong/ DCID (e.g. latLong/577521_-958960).
	// We parse it here for performance to avoid an extra database roundtrip.
	//
	// TODO(task): Revisit this optimization if we encounter valid startLocation values 
	// that are NOT latLong/ DCIDs but still need to be resolved to points, or if the 
	// assumption that dcids always contain coordinates is not true.
	if strings.HasPrefix(value, "latLong/") {
		parts := strings.Split(strings.TrimPrefix(value, "latLong/"), "_")
		if len(parts) == 2 {
			lat, err1 := strconv.ParseFloat(parts[0], 64)
			lon, err2 := strconv.ParseFloat(parts[1], 64)
			if err1 == nil && err2 == nil {
				event.GeoLocations = append(event.GeoLocations, &pbv1.EventCollection_GeoLocation{
					Geo: &pbv1.EventCollection_GeoLocation_Point_{
						Point: &pbv1.EventCollection_GeoLocation_Point{
							Latitude:  proto.Float64(lat / latLonScalingFactor),
							Longitude: proto.Float64(lon / latLonScalingFactor),
						},
					},
				})
			}
		}
	}
}

@keyurva keyurva requested a review from n-h-diaz March 13, 2026 23:41
Copy link
Contributor

@n-h-diaz n-h-diaz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for getting this done so quickly! :)

generally looks good, just wanted to clarify a few comments on how dates are handled

on geoJson escaping, it looks like current v2 does the single escape, which is how we've handled throughout for v3, so I think okay to keep for now. we can change escaping later if needed

@{force_join_order=true}
GRAPH DCGraph MATCH (event:Node)-[:Edge {predicate: 'affectedPlace', object_id: 'country/LBR'}]->(), (event)-[:Edge {predicate: 'typeOf', object_id: 'FireEvent'}]->(), (event)-[:Edge {predicate: 'startDate'}]->(dateNode:Node)
WHERE
SUBSTR(dateNode.value, 1, 7) = '2020-10'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens if the event occurs over multiple months? (ie. do we want the events to be returned if requesting another month? not sure how this is handled in current v2, but we should make sure we match the current behavior)

// Pattern: <-location{typeOf:EventType, date:Date, filter_prop:filter_val}
func parseEventCollection(req *pbv2.EventRequest, arcs []*v2.Arc) *pbv1.EventCollectionRequest {
if len(arcs) != 1 {
return nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(optional, since not backward supported: could we add some informative error messages to help understand the various reasons a request didn't parse)

if !strings.HasPrefix(edge.Value, "s2CellId/") {
event.Places = append(event.Places, edge.Value)
}
case predStartDate:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just to confirm, how is event.Dates populated? should we also add observationDates? or does this just copy from startDate? (example: https://datacommons.org/browser/fireEvent/2022-03-05_0x4737f90000000000)

(we should just match whatever v2 does for this)

},
}

var eventCollectionDcidsTestCases = []struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: since events support flexible schema, could we test a few other event types? (since we've hardcoded a few properties in the queries, want to confirm they'll work for other events too)

// TODO(task): Revisit this optimization if we encounter valid startLocation values
// that are NOT latLong/ DCIDs but still need to be resolved to points, or if the
// assumption that dcids always contain coordinates is not true.
if strings.HasPrefix(value, "latLong/") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: since we're making this assumption, could we log an error if we find any examples otherwise? (so we can track and update if needed)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants